Check Perfect Number

Check whether a number is a perfect number (sum of proper divisors equals the number).

IntermediateTopic: Module 2: Conditional Programs
Back

Java Check Perfect Number Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        int sum = 0;
        for (int i = 1; i <= n / 2; i++) {
            if (n % i == 0) {
                sum += i;
            }
        }

        if (sum == n && n != 0) {
            System.out.println(n + " is a Perfect Number");
        } else {
            System.out.println(n + " is not a Perfect Number");
        }

        sc.close();
    }
}
Output
Enter a number: 28
28 is a Perfect Number

Understanding Check Perfect Number

We sum all positive divisors less than the number; if this sum equals the number, it is perfect.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents