Perfect Number in JAVA

Perfect Number in JAVA


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 :-
  1. Get the number to check for Perfect Number
  2. Hold the number in temporary variable
  3. Store the sum of its factors excluding the number itself
  4. Compare the sum of factors with the number
  5. If both are equal print "Perfect Number"
  6. 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 :)


Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

PalPrime Number in JAVA