Home » Java Program » Perfect number program in Java

Perfect number program in Java

Last updated:

Support this post with a reaction:

3,037 views

What is Perfect Number?

A perfect number is a positive integer that is equal to the sum of all its positive divisors, excluding the number itself. In Java, we can check whether a number is perfect by finding its divisors, calculating their sum, and comparing the sum with the original number.

For example, 28 is a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and their sum is 28.

In this tutorial, you will learn how to write a Java program to check whether a given number is perfect or not using a for loop and Java 8 Stream API.

A perfect number is a number whose sum of proper positive divisors is equal to the number itself.

A proper divisor is a positive integer that divides a number completely without leaving a remainder, excluding the number itself.

Mathematical representation:

N=∑d|N, d<Nd N = \sum_{d\mid N,\ d<N} d

Where:

  • N represents the given number.
  • d represents a proper divisor of N.
  • The sum includes all positive divisors except N itself.

How this Java program will behave?

The Java program checks whether a number is perfect by following these steps:

  1. Read an integer from the user.
  2. Initialize a variable sum to 0.
  3. Find all proper divisors of the given number.
  4. Add each divisor to the sum variable.
  5. Compare the calculated sum with the original number.
  6. If both values are equal, print that the number is perfect; otherwise, print that it is not perfect.

After the calculation it will give you appropriate output.

Program 1: Perfect Number Program in Java Using For Loop

The following Java program uses a for loop to find all proper divisors of a given number and calculate their sum.

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 number = sc.nextInt();

        int sum = 0;

        if (number <= 1) {
            System.out.println(number + " is not a perfect number");
        } else {

            for (int i = 1; i <= number / 2; i++) {

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

            if (sum == number) {
                System.out.println(number + " is a perfect number");
            } else {
                System.out.println(number + " is not a perfect number");
            }
        }

        sc.close();
    }
}

Output 1:

Enter a number: 28
28 is a perfect number

Output 2:

Enter a number: 15
15 is not a perfect number

Explanation of the Java Program

Let’s understand the important statements used in the program.

StatementExplanation
Scanner sc = new Scanner(System.in);Reads input from the user.
int sum = 0;Initializes the sum of divisors.
number <= 1Handles numbers that cannot be perfect.
for (int i = 1; i <= number / 2; i++)Checks possible proper divisors.
number % i == 0Checks whether i divides the number completely.
sum = sum + i;Adds the divisor to the sum.
sum == numberDetermines whether the number is perfect.

Dry Run of the Program

Let’s understand how the program works for the input 28.

Iterationi28 % iDivisor?Sum
110Yes1
220Yes3
331No3
440Yes7
553No7
664No7
770Yes14
884No14
991No14
10108No14
11116No14
12124No14
13132No14
14140Yes28

At the end:

  • Original number = 28
  • Sum of proper divisors = 28
  • Both values are equal.

Therefore, 28 is a perfect number.

Program 2: Perfect Number Program in Java Using Java 8 Stream API

Java 8 provides the Stream API, which allows us to process collections and sequences of values using operations such as filter() and sum().

We can use IntStream.range() to generate numbers from 1 to the given number (excluding the number itself).

The filter() method selects only the numbers that divide the given number completely, and the sum() method calculates their total.

Java Code:

import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

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

        if (number <= 1) {
            System.out.println(number + " is not a perfect number");
        } else {

            int sum = IntStream.range(1, number)
                    .filter(i -> number % i == 0)
                    .sum();

            if (sum == number) {
                System.out.println(number + " is a perfect number");
            } else {
                System.out.println(number + " is not a perfect number");
            }
        }

        sc.close();
    }
}

Output:

Enter a number: 28
28 is a perfect number

Explanation of Java 8 Stream API Methods

MethodDescription
IntStream.range(1, number)Generates integers starting from 1 and ending at number -1.
filter()Selects numbers that divide the given number without a remainder.
sum()Calculates the sum of all selected divisors.

Program 3: Optimized Perfect Number Program in Java

We can optimize the divisor-checking process by checking divisors only up to the square root of the given number.

The reason is that divisors occur in pairs. For example, the divisor pair of 28 is (2, 14) and (4, 7).

Instead of checking every number up to number / 2, we can find divisor pairs and add both divisors to the sum.

Java 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 number = sc.nextInt();

        if (number <= 1) {
            System.out.println(number + " is not a perfect number");
        } else {

            int sum = 1;

            for (int i = 2; i <= number / i; i++) {

                if (number % i == 0) {

                    sum += i;

                    int pair = number / i;

                    if (pair != i) {
                        sum += pair;
                    }
                }
            }

            if (sum == number) {
                System.out.println(number + " is a perfect number");
            } else {
                System.out.println(number + " is not a perfect number");
            }
        }

        sc.close();
    }
}

Output:

Enter a number: 28
28 is a perfect number

Why is this approach optimized?

For a number N, if i divides N, then N / i is also a divisor.

For example, for 28:

  • 2 × 14 = 28
  • 4 × 7 = 28

Therefore, we only need to check divisors up to the square root of N. The condition i <= number / i avoids potential multiplication overflow from i * i.