Perfect number program - Java

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

A Java program to find if a number is perfect number or not. Means the sum of all the factors of the number is equal to the number or not.


import java.util.Scanner;

class fifthapp
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("\nInsert a number :: ");
        int number = sc.nextInt();
       
        int i=1, sum=0;
       
        for(i=1; i<number; i++)
        {
            if(number%i == 0)
            {
                sum += i;
            }
        }
       
        if(sum == number)
        {
            System.out.println("\nThis is a perfect number.");           
        }
        else
        {
            System.out.println("\nThis is not a perfect number.");
        }       
    }
}

Post a Comment