Subscribe Us

Perfect Number In Java

Perfect Number In Java

Java Program To Check Perfect Number or Not

In mathematics, a perfect number is a positive integer that is
equal to the sum of its positive divisors, excluding the number itself.

For Example,
28 is a positive number that is completely divisible by 1, 2, 4, 7 and 14.
We know that the number is also divisible by itself but we will exclude it in the addition of divisors.
When we add these divisors (1 + 2 + 4 + 7 + 14 = 28), it produces 28, which is equal to the number that we have considered.
So, we can say that 28 is a perfect number.

To check if a number is a Perfect Number or not in Java
you can use the following algorithm:
  1. Read the input number.
  2. Initialize a variable sum to 0.
  3. Iterate through all the numbers from 1 to number/2 (excluding number itself).
    • For each iteration, check if the current number is a divisor of the input number.
    • If the current number is a divisor, add it to the sum.
  4. After the loop, check if the sum is equal to the input number.
    • If they are equal, the number is a Perfect Number; otherwise, it is not.
  5. Print the result.

This algorithm calculates the sum of the divisors of the input number and compares it with the input number to determine if it is a Perfect Number.

Here is an example implementation in Java

Source Code

// Java Program To Check Perfect Number
import java.util.*;
public class PerfectNumber 
 {
  public static void main(String args[])
   {
     Scanner in = new Scanner(System.in);
     int num , i , sum = 0 ;
     System.out.print("Enter a Number To Check : ");
     num=in.nextInt();
     for(i=1;i<=num/2;i++)
      {
        if(num%i==0)
         {
           System.out.print(i+" ");
           sum=sum+i;
         }
      }
     System.out.println(); 
     System.out.println("Sum of Factors of a Given Number : "+sum);
     if(sum==num)
      System.out.print("It is a Perfect Number .");
     else
      System.out.print("It is Not a Perfect Number .");
   }
 }
 

Output

Sample Input :
Enter a Number To Check : 28
Sample Output:
1 2 4 7 14
Sum of Factors of a Given Number : 28
It is a Perfect Number

Sample Input :
Enter a Number To Check : 10
Sample Output:
1 2 5
Sum of Factors of a Given Number : 8
It is Not a Perfect Number

Looping Related Programs