top of page
Writer's pictureSatyam Gupta

Perfect Number in JAVA

Perfect Number

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

Input : 6

Sum of Factors : 1 + 2 + 3 = 6

Output : It is a Perfect Number


Factors of 28 : 1,2,4,7,14

Input : 28

Sum of Factors : 1 + 2 + 4 + 7 + 14 = 28

Output : It 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 :-


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

 

Note : The program is written in the easiest way possible so try understand it. If you face any problem in understanding this program than feel free to contact/comment.


All the Best :)

Keep Learning :)

26 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page