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
- Read an integer
xfrom the user. - Initialize an integer
sumto 0. - Start a
forloop fromi = 1up tox / 2. - If
xis divisible byi(x % i == 0), additosum. - After the loop, compare
sumto the original numberx. 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 / 2because 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.