Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to check a given number is perfect or not.

Java Code Example — Simple Programs

ADVERTISEMENT

Java Program to check a given number is perfect or not.

Objective

Write a Java program to check if a given positive integer is a Perfect number.

Algorithm / Approach

  1. Read an integer x from the user.
  2. Initialize an integer sum to 0.
  3. Start a for loop from i = 1 up to x / 2.
  4. If x is divisible by i (x % i == 0), add i to sum.
  5. After the loop, compare sum to the original number x. If they match, it is a perfect number.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num: ");
  int x = s.nextInt();
  int sum = 0;
  for(int i = 1; i <= x/2; i++) {
   if(x%i ==0) {
    sum = sum+i;
   }
  }
  if(sum==x) {
   System.out.print("Perfect number");
  }
  else {
   System.out.print("NOT Perfect Number");
  }
 }
}

Expected Output

Enter a Num: 28
Perfect number

Explanation of the Program

  • A Perfect Number is a positive integer that is equal to the sum of its proper divisors (excluding itself).
  • For example, 28 has divisors 1, 2, 4, 7, and 14. Their sum is 1 + 2 + 4 + 7 + 14 = 28.
  • The loop only iterates up to x / 2 because no proper divisor can be greater than half of the number.

Complexity

Time Complexity O(n) - The loop runs exactly n/2 times.
Space Complexity O(1)

Common Mistakes

  • Iterating the loop all the way up to x, which would erroneously include the number itself in the divisor sum.
ADVERTISEMENT