Find Perfect Number in Java

Previous
Next

In this article, we are going to find whether a number is perfect or not using Java.


A number is called a perfect number if the sum of its divisors is equal to the number. The sum of divisors excludes the number. There may be several approaches to find the perfect number.
For example:

28 is perfect number:
– 28’s divisors are 1, 2, 4, 7, 14
– sum of divisors of 28 excluding itself is 28.

Here, we are using two main approaches iterative and recursive approach.

Let’s see the example.

Iterative approach

In this example, we are using the while loop to find divisors of the number and then get sum of them.
Here are the steps:

  1. Initiaze sum=0 and loop variable i=1.
  2. Iterate a while loop until condition i<=number/2 is false.
  3. Check remainder of number%i using modulo operator. If remainder is 0, then add it to the sum.
  4. If sum is equals to number after all iterations, then it is perfect number.

Output

It is Perfect Number

Recursive approach

We can use recursion technique, if don’t want to use while loop. It reduces code statements but provides the accurate result.
Here are the steps:

  1. Initialize static variable sum=0.
  2. Create a function findPerfect() which will take two parameters number and div
  3. Check if div<=number/2 is true. This will be the terminal condition for recursion.
    1. Check remainder of number%i using modulo operator. If remainder is 0, then add it to the sum.
    2. Increment div
    3. Call findPerfect() recursively.
  4. If returned output of findPerfect() is equals to number, then it is perfect number.
    See the example below.

Output

It is Perfect Number

That’s all about how to find Perfect Number in Java.

Previous
Next

Add Comment