Find Perfect Number in Java

What is a perfect number?

A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. These numbers are positive numbers that are less than the number itself.

Let’s take an example 6.

  • Divisors of 6 = 1,2,3,6
  • The sum of Divisors of 6 = 1+2+3
  • Thus we can say that 6 is a perfect number.

So the next perfect number is 28, 496, 8128 so on.

public class PerfectNumber {

    public static boolean isPerfect(int num) {
        if (num <= 1) {
            return false; // Perfect numbers are positive integers greater than 1.
        }

        int sumOfDivisors = 1; // Initialize with 1 because 1 is always a divisor.

        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                sumOfDivisors += i;

                if (i != num / i) {
                    sumOfDivisors += num / i;
                }
            }
        }

        return sumOfDivisors == num;
    }

    public static void main(String[] args) {
        int numberToCheck = 28; // Replace with the number you want to check for perfection.
        if (isPerfect(numberToCheck)) {
            System.out.println(numberToCheck + " is a perfect number.");
        } else {
            System.out.println(numberToCheck + " is not a perfect number.");
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts