Perfect number or not using Java

Perfect number or not using java :

Perfect number is a number whose sum of factors is equal to the given number. Let us consider an example for better understanding.

Example :

  • Suppose a number  is 28 ;
  • Factors of 28 are : 1, 2, 4, 7, 14 ;
  • Sum of Factors of the number  = 28 ;

Here the sum of factors of the number is equal to the given number ;

So, 28 is a Perfect Number. 

In this article we will create a java program to check whether a given number is a Perfect number or not.

Perfect number or not using java

Working :

Step 1 : Ask the user to enter a number.

Step 2 : Declare a variable for storing sum.

Step 3 : Use a loop to find the factors of the given number and store its sum.

Step 4 : Calculate the sum of factors of the given number.

Step 5 : Compare whether the sum is equal to the given number or not.

  • If both numbers are equal, then the given number is Perfect Number.
  • Else the number is not a Perfect Number. 

Code in Java :

//Java program to check whether a number is perfect or not 
import java.util.Scanner;
public class perfect_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
//declare a variable to store sum of factors
int sum = 0;
for(int i = 1 ; i < number ; i++)
{
if(number % i == 0)
sum = sum + i;
}
//comparing whether the sum is equal to the given number or not
if(sum == number)
System.out.println("Perfect Number");
else
System.out.println("Not an Perfect Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a number : 6
Perfect Number

Enter a number : 15
Not an Perfect Number

Enter a number : 496
Perfect Number

Please Login/Signup to comment