Perfect Number in JAVA
Perfect Number in JAVA
A Perfect Number is a positive integer that is equal to the sum of factors i.e. the sum of its positive factors excluding the number itself.
Example - Factors of 6 = 1+2+3 = 6 . 6 is a Perfect Number
Algorithm and Program below :-
ALGORITHM :-
- Get the number to check for Perfect Number
- Hold the number in temporary variable
- Store the sum of its factors excluding the number itself
- Compare the sum of factors with the number
- If both are equal print "Perfect Number"
- If not print "Not a Perfect Number"
PROGRAM below:-
import java.io.*;
import java.util.*;
class Perfect
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
int n,p,s=0,i;
System.out.println("Enter No.");
n= in.nextInt(); // Input number from user
p=n; // store the entered number in "p" variable
for(i=1;i<n;i++) // loop to find the factors
{
if(n%i==0) // Cpndition for factors of number
{
s=s+i; // storing sum of factors excluding number
}
}
if(s==p) //comparing sum of factors with number
{
System.out.println("It is a Perfect Number : "+p);
}
else
{
System.out.println("It is not a Perfect Number : "+p);
}
} // end of main method
} // end of class
All the Best :)
Keep Learning :)
All the Best :)
Keep Learning :)
Comments
Post a Comment