You are here: Home / Topics / Program to check whether given number is Perfect or not in Java

Program to check whether given number is Perfect or not in Java

Filed under: Java on 2023-08-18 06:49:47

Before proceeding to our program code, we must see what is perfect number.

What is perfect number?

In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. Illustration of the perfect number status of the number 6.

Code

// Program to check whether the given number is PERFECT or NOT.
// Logic (like 6 and 28) (1 + 2 + 3 + 6) = (2*6)

class  PerfectTest
{
public static void main( String args[ ] )
{
 int  i, t, n, sum;

 n = 28;

 sum = 0;
 for( i=1 ; i<=n/2 ; i++ )
 {
  if( n % i == 0 )
  {
   sum = sum + i;
  }
 }

 if( n == sum )
  System.out.println( "\n The Number " + n + " is a PERFECT Number." );
 else
  System.out.println( "\n The Number " + n + " is NOT a PERFECT Number." );
}
}


Output:

The Number 28 is a PERFECT Number.

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.