# Finding Perfect Numbers in a Range Using Java

A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. For example, 6 is a perfect number since the sum of its divisors (1 + 2 + 3) is equal to 6.

## Finding Perfect Numbers in a Range Using Java

The following Java program finds all perfect numbers between two given numbers. The following program prints perfect numbers between 1 and 10000. We iterate through the range of values and then check whether each number is a perfect number or not.

To check whether a number is perfect, we first find all the proper divisors and then add them up. We then check whether it is same as the given number. The first 4 perfect numbers are 6,28,496 and 8128.

import java.io.IOException; // Finding perfect numbers in a range using Java public class PerfectNumbersInRange { public static void main(String[] args) throws IOException { int starting_number = 1; int ending_number = 10000; System.out.println("Perfect Numbers between "+starting_number+ " and "+ending_number); for (int i = starting_number; i <= ending_number; i++) { if (isPerfectNumber(i)) { System.out.println(i+" is a perfect number"); } } } /** * Checks whether the given number is a perfect number * @param number * @return */ public static boolean isPerfectNumber(int number) { int sum=0; for(int i=1; i<=number/2; i++) { if(number%i == 0) { sum += i; } } if(sum==number) { return true; }else { return false; } } }