Home / Programs / check if a number is a perfect number in Java
Programming Example

check if a number is a perfect number in Java

👁 170 Views
💻 Practical Program
📘 Step by Step Learning

Information & Algorithm

Given Input:

28

Expected Output:

28 is a perfect number.

Program Code

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.");
        }
    }
}

Output

28 is a perfect number.

Explanation

  • isPerfectNumber(int number) method checks if number is a perfect number.
  • It initializes sum to 1 (since 1 is always a divisor).
  • It iterates through numbers from 2 up to the square root of number.
  • For each divisor i, it checks if number % i == 0.
  • If true, i and number / i are divisors.
  • It accumulates these divisors in sum.
  • Finally, it checks if sum equals number to determine if it's a perfect number.

How to learn from this program

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.