Perfect number

A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.

Logic

To check if the number is perfect or not we have to run one loop from 1 to N and sum all the numbers between 1 to N, if the sum is equal to N then it is a perfect number.

Program

import java.util.Scanner;

public class CheckPerfectNumber {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int i, num, sum = 0;

        // Take input from user
        System.out.print("Enter any number : ");
        num = scanner.nextInt();

        // Calculate sum of all proper divisors
        for(i = 1; i < num; i++) {

            if(num % i == 0) {
                sum += i;
            }
        }

        // Check whether the sum of divisors is equal to num
        if(sum == num) {
            System.out.println("\n" + num + " is PERFECT NUMBER");
        } else {
            System.out.println("\n" + num + " is NOT PERFECT NUMBER");
        }
    }

}

Output

Enter any number : 5
5 is NOT PERFECT NUMBER