Java Program To Check Perfect Number or Not
In mathematics, a perfect number is a positive integer that is
equal to the sum of its positive divisors, excluding the number itself.
For Example,
28 is a positive number that is completely divisible by 1, 2, 4, 7 and 14.
We know that the number is also divisible by itself but we will exclude it in the addition of divisors.
When we add these divisors (1 + 2 + 4 + 7 + 14 = 28), it produces 28, which is equal to the number that we have considered.
So, we can say that 28 is a perfect number.
you can use the following algorithm:
- Read the input number.
- Initialize a variable sum to 0.
- Iterate through all the numbers from 1 to number/2 (excluding number itself).
- For each iteration, check if the current number is a divisor of the input number.
- If the current number is a divisor, add it to the sum.
- After the loop, check if the sum is equal to the input number.
- If they are equal, the number is a Perfect Number; otherwise, it is not.
- Print the result.
This algorithm calculates the sum of the divisors of the input number and compares it with the input number to determine if it is a Perfect Number.
Here is an example implementation in JavaSource Code
// Java Program To Check Perfect Number
import java.util.*;
public class PerfectNumber
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int num , i , sum = 0 ;
System.out.print("Enter a Number To Check : ");
num=in.nextInt();
for(i=1;i<=num/2;i++)
{
if(num%i==0)
{
System.out.print(i+" ");
sum=sum+i;
}
}
System.out.println();
System.out.println("Sum of Factors of a Given Number : "+sum);
if(sum==num)
System.out.print("It is a Perfect Number .");
else
System.out.print("It is Not a Perfect Number .");
}
}
Output
Sample Input :
Enter a Number To Check : 28
Sample Output:
1 2 4 7 14
Sum of Factors of a Given Number : 28
It is a Perfect Number
Sample Input :
Enter a Number To Check : 10
Sample Output:
1 2 5
Sum of Factors of a Given Number : 8
It is Not a Perfect Number
Looping Related Programs
- Java Program to Check Prime Number or Not
- Java Program to Check Twin Prime Number or Not
- Java Program to Check Perfect Number or Not
- Java Program to Check Spy Number or Not
- Java Program to Check Neon Number or Not
- Java Program to Check Duck Number or Not
- Java Program to Check Niven or Harshad Number or Not
- Java Program to Check Palindrome Number or Not
- Java Program to Check Armstrong Number or Not
- Java Program to Check Strong (Krishnamurthy) Number or Not
- Java Program to Check Automorphic Number or Not
- Java Program to Check Happy Number Or Not