# Perfect Number Program in Java

In this section, we will learn what is a perfect number in Java and also create Java programs to check if the given number is perfect or not. Also, we will create a Java program for finding all the perfect numbers between the given range. The perfect number program frequently asked in Java coding tests and academics.

## What is a perfect number in Java?

A number whose sum of factors (excluding the number itself) is equal to the number is called a perfect number. In other words, if the sum of positive divisors (excluding the number itself) of a number equals the number itself is called a perfect number. Let's understood it through an example.

### Example of a Perfect Number

Let's take the number 496 and heck it is a perfect number or not.

First, we find the factors of 496 i.e. 1, 2, 4, 8, 16, 31, 62, 124, and 248. Let's find the sum of factors (1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 +248 = 496). We observe that the sum of factors is equal to the number itself. Hence, the number 496 is a perfect number. Similarly, we can check other numbers also.

Some other perfect numbers are 6, 8128, 33550336, 8589869056, etc.

## Steps to Find Perfect Number

1. Read or initialize a number (n).
2. Declare a variable (s) for storing sum.
3. Find the factors of the given number (n) by using a loop (for/ while).
4. Calculate the sum of factors and store it in a variable s.
5. Compare the sum (s) with the number (n):
• If both (s and n) are equal, then the given number is a perfect number.
• Else, the number is not a perfect number.

Let's implement the above steps in a Java program.

## Perfect Number Java Programs

There are the following ways to find the perfect number in Java:

• Using while Loop
• Using Method
• Using Recursion

### Using while Loop

PerfectNumberExample1.java

Output 1:

```Enter the number: 28
28 is a perfect number.
```

Output 2:

```Enter the number: 4558
4558 is not a perfect number.
```

### Using Method

PerfectNumberExample2.java

Output 1:

```Enter the number: 6
6 is a perfect number.
```

Output 2:

```Enter the number: 1234
1234 is not a perfect number.
```

### Using Recursion

PerfectNumberExample3.java

Output 1:

```Enter the number: 8128
8128 is a perfect number.
```

Output 2:

```Enter the number: 7866
7866 is a perfect number.
```

## Perfect Numbers Between Given Range

The following program finds all the perfect numbers between a given range.

PerfectNumberExample3.java

Output:

```Perfect Numbers between 2 to 10000 are:
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
```

### Feedback

• Send your Feedback to feedback@javatpoint.com