In this article, we are going to find whether a number is perfect or not using Java.
[toc]
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’s divisors are 1, 2, 4, 7, 14
– sum of divisors of 28 excluding itself is 28.
[su_note note_color=”#f5f7f7″]
[su_list icon=”icon: check”]
Recommended read
[/su_list]
[/su_note]
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:
- Initiaze
sum=0and loop variablei=1. - Iterate a while loop until condition
i<=number/2is false. - Check remainder of
number%iusing modulo operator. If remainder is 0, then add it to thesum. - If
sumis equals to number after all iterations, then it isperfect number.public 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
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 parametersnumberanddiv - Check if
div<=number/2is true. This will be the terminal condition for recursion.- Check remainder of
number%iusing 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.
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
That's all about how to find Perfect Number in Java.