Select Page

Perfect Number Program in Java

A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a perfect number. This is because all the factors of the number 28, excluding the number itself are: 1, 2, 4, 7, 14, and their sum is 1 + 2 + 4 + 7 + 14 = 28. The perfect number program in Java checks whether the given is the perfect number or not.

The steps required to find the perfect are as follows:

Step 1: Declare a variable x.

Step 2: Take input from the user and assign it to the variable x.

Step 3:  Declare another variable sumOfFactors. Assign value zero to it, i.e., sumOfFactors = 0.

Step 4: Find all the factors of x, barring x itself.

Step 5: Store the sum of all factors found in step 3, in the variable sumOfFactors.

Step 6: Compare sumOfFactors and x to check whether they are equal or not; if they are equal, the input number is perfect number; otherwise, not.

There are two ways to implement the above steps: one is iterative, and another is recursive. Let’s start with the iterative approach.

Iterative Approach

Filename: PerfectNumber.java

Output 1:

Output 2:

Explanation:  In the above code, we are storing the input from the user in the variable x. Then, using the Java for-loop, we are finding the factors of x. The iterations start from 1 and go till x / 2. This way, we are excluding the number x from the factors. Every number from 1 to x / 2 is checked for the factors of x. If the factor is found, that factor is added to the variable sumOfFactors. Eventually, we are checking the sumOfFactors with x and displaying the result accordingly.

Recursive Approach

Filename: PerfectNumber1.java

Output1:

Output2:

Explanation: Instead of Java for-loop, we have relied upon the recursive call to find the factors of x. The approach still remains the same, i.e., to check every number between 1 and x / 2 in order to get the factors of x, excluding x itself.

To find perfect numbers between 1 to 500

The following Java program displays perfect numbers present between 1 to 500.

Filename: PerfectNumber2.java

Output:

Explanation: In the main method, the Java for-loop is iterating from 1 to 500. In each iteration, we are calling the method isPerfectNo(), whose return type is Boolean. The method takes a number (n) in its argument and checks whether that number, n, is a perfect number or not. If n is a perfect number, the method returns true; otherwise, false. For those numbers, where the method isPerfectNo() has returned false, are discarded, and the rest of the numbers are printed on the console.