Perfect Number Java Program (using Functions)

Write a program in java to accept a number and check the number is Perfect number or not using the following Functions.

[Perfect: If the Sum of factors excluding the number itself is equal to the original number then it is termed as a Perfect number ]
Example : 6, 28 etc.

static void accept( ) : to accept the number.

static void perfect(int a): to check the number is Perfect or not.

Write a main( ) method to call the other methods.

import java.util.Scanner;
class Perfect
{
    static int n;
    
    static void accept()
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        n = in.nextInt();
    }
    
    static void perfect(int a)
    {
        int sum=0;
        for(int i=1; i<a; i++)
        {
            if(a%i==0)
            {   //if is a factor of a
                //sum=sum+i;
                sum+=i;
            }
        }
        if(sum==a)
            System.out.println(a+" is a Perfect Number");
        else
            System.out.println(a+" is not a Perfect Number");
    }
    
    public static void main(String args[])
    {
        accept();
        perfect(n);
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *