March 14 2015

Perfect Number Program In Java

Perfect Number Program In Java

A perfect number is a positive integer that is equal to the sum of its proper divisors.

Example – 6,28,496 ,8128 etc

The factors of 6 are 1, 2, 3 and 6.
1 + 2 + 3 = 6

The factors of 28 are 1, 2, 4, 7, 14 and 28.
1 + 2 + 4 + 7 + 14 = 28

Algorithm

  • Take the number from the user(number)

  • Iterate from 1 to the number-1(i)

  • Check whether i is divisor of number or not

  • Add the number to sum(sumOfDivisors) if it is a divisor

  • If number is equal to sumOfDivisors,it is perfect number

  • Print the result

Perfect Number Program In Java

package com.answersz.impprograms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// Perfect number program in java
public class PerfectNumberProgram {

 public static void main(String args[]) throws IOException {

 System.out.println("Enter number to check perfect number or not : ");

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int number = Integer.parseInt(br.readLine());

 int sumOfDivisors = 0;
 for (int i = 1; i < number; i++) {
 if (number % i == 0) {
 sumOfDivisors = sumOfDivisors + i;
 }
 }

 if (number == sumOfDivisors) {
 System.out.println(number + " is a perfect number");
 } else {
 System.out.println(number + " is not a perfect number");

 }
 }
}

Output

Enter number to check perfect number or not :

28

28 is a perfect number

Enter number to check perfect number or not :

34

34 is not a perfect number


Copyright © 2014. All rights reserved.

Posted March 14, 2015 by answersz in category Bluej Java Programs for ICSE Class 10 and 9 Practice, Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*