What is Perfect Number?
A number whose sum of factors (excluding the number itself) is equal to the number is called a perfect number.
1) Using While Loop
Code:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
long n, sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number: ");
n=sc.nextLong();
int i=1;
//executes until the condition becomes false
while(i <= n/2)
{
if(n % i == 0)
{
//calculates the sum of factors
sum = sum + i;
}
i++;
}
//compares sum with the number
if(sum==n)
{
//prints if sum and n are equal
System.out.println(n+" is a perfect number.");
}
else{
//prints if sum and n are not equal
System.out.println(n+" is not a perfect number.");
}
}
}
Output:
Perfect Number Between a Given Range
Code:
public class Main
{
//function checks if the given number is perfect or not
static boolean isPerfectNumber(int num)
{
//variable stores the sum of divisors
int sum = 1;
//determines all the divisors of the given number and adds them
for (int i = 2; i * i <= num; i++)
{
if (num % i==0)
{
if(i * i != num)
sum = sum + i + num / i;
else
//calculates the sum of factors
sum = sum + i;
}
}
if (sum == num && num != 1)
//returns true if both conditions (above) returns true
return true;
//returns false if any condition becomes false
return false;
}
//driver code
public static void main (String args[])
{
System.out.println("Perfect Numbers between 2 to 10000 are: ");
//loop executes until the condition n<10000 becomes false
for (int n = 2; n < 10000; n++)
//calling function
if (isPerfectNumber(n))
//prints all perfect number between given range
System.out.println(n +" is a perfect number");
}
}
Output:
Tags:
Java Programs