Java Program to Check if a Given Number is Perfect Number
Last Updated :
30 Jul, 2023
A number is said to be a perfect number if the sum of its proper divisors ( i.e. all positive divisors excluding the number itself )is equal to that number itself. Aliquot sum is the sum of divisors of a number, excluding the number itself. Hence, a number is a perfect number only if it is equal to its aliquot sum. All known perfect numbers are even. In this article, we will learn how to Check Perfect Numbers in Java.
Example 1:
n = 9
Proper Divisors of 9 are 1 and 3.
Sum = 1+3 = 4 ≠9
⇒ 9 is not a perfect number.
Example 2:
n = 6
Proper Divisors of 6 are 1, 2 and 3.
Sum = 1+2+3 = 6 = 6
⇒ 6 is a perfect number
So, we basically have to find the sum of the proper divisors of a number.
1. Using Loop to Check Perfect Number in Java
A Simple Solution is to go through every number from 1 to n-1 and check if it is a divisor and if it is, then add it in the sum variable and at the end check if the sum is equal to the number itself, then it is a perfect number otherwise not.
Below is the implementation of the above method:
Java
class GFG {
static boolean isPerfect( int n)
{
if (n == 1 )
return false ;
int sum = 1 ;
for ( int i = 2 ; i < n; i++) {
if (n % i == 0 ) {
sum += i;
}
}
if (sum == n)
return true ;
return false ;
}
public static void main(String[] args)
{
int n = 6 ;
if (isPerfect(n))
System.out.println(n + " is a perfect number" );
else
System.out.println(
n + " is not a perfect number" );
}
}
|
Output
6 is a perfect number
The complexity of the above method
2. Using Square root to Check Perfect Number in Java
An Efficient Solution is to go through numbers till the square root of n.
If i is a divisor then n/i is also a divisor.
Java
class GFG {
static boolean isPerfect( int n)
{
if (n == 1 )
return false ;
int sum = 1 ;
for ( int i = 2 ; i * i <= n; i++) {
if (n % i == 0 ) {
if (i * i == n)
sum += i;
else
sum += i + (n / i);
}
}
if (sum == n)
return true ;
return false ;
}
public static void main(String[] args)
{
int n = 6 ;
if (isPerfect(n))
System.out.println(n + " is a perfect number" );
else
System.out.println(
n + " is not a perfect number" );
}
}
|
Output
6 is a perfect number
The complexity of the above method
Time Complexity: O(√n)
3. Recursive Approach to Check Perfect Number in Java
Below is the implement the above method:
Java
import java.util.*;
public class GFG {
static long sum = 0 ;
static long isPerfect( long num, int i)
{
if (i <= num / 2 ) {
if (num % i == 0 ) {
sum = sum + i;
}
i++;
isPerfect(num, i);
}
return sum;
}
public static void main(String args[])
{
long number = 28 , s;
int i = 1 ;
s = isPerfect(number, i);
if (s == number)
System.out.println(number
+ " is a perfect number" );
else
System.out.println(
number + " is not a perfect number" );
}
}
|
Output
28 is a perfect number
The complexity of the above method
Time Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...