The number which is equal to the sum of its divisors is called a perfect number. Read the entered long number, assigned to the long variable n. While loop iterates until the condition (i<=n/2) is false. If the remainder of n/i=0 then add i value to the sum and increase the i value. After all the iterations compare the number with the sum, if both are equal then prints the number as a perfect number.
Example:
n = 6, i = 1 condition at while is 1 <= 3 is true, here 6%i = 0 is true so sum = 1,
i = 2, 2 < 3 is true, 6%2 = 0 is true so sum = 1+2=3,
i=3, 3<=3 is true, 6%3=0 is true so sum=3+3=6, for i=4 the while loop terminates and compares the sum value with n, both are equal, so it prints 6 is a perfect number.
Implementation
import java.util.Scanner;
class Perfect
{ public static void main(String arg[])
{
long n,sum= 0 ;
Scanner sc= new Scanner(System.in);
System.out.println( "Enter a number" );
n=sc.nextLong();
int i= 1 ;
while (i<=n/ 2 )
{
if (n%i== 0 )
{
sum+=i;
}
i++;
}
if (sum==n)
{
System.out.println(n+ " is a perfect number" );
}
else
System.out.println(n+ " is not a perfect number" );
}
} |
Output:
The time complexity is O(n), where n is the input number.
The auxiliary space is O(1)
Example :
import java.io.*;
public class PerfectNumber {
public static void main(String[] args) {
int number = 1 ;
while (number <= 10000 ) {
int sum = 0 ;
// Find all the factors of the current number and add them up
for ( int i = 1 ; i < number; i++) {
if (number % i == 0 ) {
sum += i;
}
}
// If the sum of the factors equals the number, it's a perfect number
if (sum == number) {
System.out.println(number + " is a perfect number" );
}
number++;
}
}
} |
output :
6 is a perfect number 28 is a perfect number 496 is a perfect number 8128 is a perfect number