In this article, we are going to find whether a number is perfect
or not using Java.
Table of Contents
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.
– 28’s divisors are 1, 2, 4, 7, 14
– sum of divisors of 28 excluding itself is 28.
Recommended read
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:
- Initiaze
sum=0
and loop variablei=1
. - Iterate a while loop until condition
i<=number/2
is false. - Check remainder of
number%i
using modulo operator. If remainder is 0, then add it to thesum
. - If
sum
is equals to number after all iterations, then it isperfect number
.
12345678910111213141516171819202122public class Main{public static void main(String args[]){int number = 28;int sum = 0;int i = 1;while(i<=number/2){if(number%i == 0){sum+=i;}i++;}if(sum == number)System.out.println("It is Perfect Number");else System.out.println("It is not 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:
- Initialize static variable
sum=0
. - Create a function
findPerfect()
which will take two parametersnumber
anddiv
- Check if
div<=number/2
is true. This will be the terminal condition for recursion.- Check remainder of
number%i
using modulo operator. If remainder is 0, then add it to thesum
. - Increment
div
- Call
findPerfect()
recursively.
- Check remainder of
- If returned output of
findPerfect()
is equals to number, then it isperfect number
.
See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Main { static int number = 8128; static int sum = 0; static int div = 1; static int findPerfect(int number, int div) { { if(div<=number/2) { if(number%div==0) { sum+=div; } div++; findPerfect(number,div); } return sum; } } public static void main(String args[]) { int result = findPerfect(number,div); if(result == number) System.out.println("It is Perfect Number"); else System.out.println("It is not Perfect Number"); } } |
Output
It is Perfect Number
That’s all about how to find Perfect Number in Java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.