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

                        

🖥 Program 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.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.