Programming Example
check if a number is a perfect number in Java
28
28 is a perfect number.
public class PerfectNumberChecker {
public static boolean isPerfectNumber(int number) {
if (number <= 1) {
return false; // Perfect numbers are positive integers greater than 1
}
int sum = 1; // Start with 1 as 1 is always a divisor
// Find all divisors up to the square root of the number
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
sum += i; // i is a divisor
if (i != number / i) {
sum += number / i; // number / i is also a divisor (if it's different)
}
}
}
// If sum of divisors equals the number, then it's a perfect number
return sum == number;
}
public static void main(String[] args) {
int number = 28; // Example number to check
if (isPerfectNumber(number)) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
}
}
28 is a perfect number.
isPerfectNumber(int number) method checks if number is a perfect number.sum to 1 (since 1 is always a divisor).number.i, it checks if number % i == 0.i and number / i are divisors.sum.sum equals number to determine if it's a perfect number.First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.