# Java Program to Find Perfect Number

The following Java program displays the available perfect numbers within a defined range of numbers. I use the Java **for-loop** to iterate between the minimum and maximum numbers to be checked.

If a positive integer is equal to the sum of its divisors, we call it a perfect number, assuming the divisors don’t include the number itself. For instance, the factors of 6 are 1, 2 and 3. If we add the factors, that is 1 + 2 + 3, we get 6. Since this number is the same as the original number . It is a **perfect** number.

As the following snippet shows, we first find the factors of a given number and then add what we found to compare their sum with the original number

```
for(int i = 1; i<=number/2; i++){
if(number%i ==0){
sum += i;
}
}
if(sum == number){
System.out.println(sum);
}
```

We check up to **number/2** because beyond that we get only the number itself. So if the given number is 28, the upper limit of **‘i**‘ is **28/2** 0r **14**.

As

` sum += i;`

shows, we add the factors for us to compare with the main number.

The full program is listed below.

I used a for loop to check the numbers below 10,000.

If you are behind a powerful computer, you can increase the size, but mine struggles beyond that.

Please note you can use the method without a loop control if you wish.

```
public class PerfectNumber{
public static void calPefectNumber(int number){
int sum = 0;
for(int i = 1; i<=number/2; i++){
if(number%i ==0){
sum += i;
}
}
if(sum == number){
System.out.println(sum);
}
}
public static void main(String[] args) {
System.out.println("Perfect numbers:");
for(int i= 1; i<=10000; i++)
calPefectNumber(i);
}
}
```

The output of this particular request is :

**Perfect numbers:**

**6**

**28**

**496**

**8128**

## Leave a Reply