Finding Perfect Square Numbers in a Range Using Java

Perfect square numbers are natural numbers which can be expressed in the form n = a * a. Hence any number which is the result of multiplying a number with itself is known as a perfect square number.  For example, 9 is a perfect square number since 9 = 3 * 3.

Finding Perfect Square Numbers in a Range Using Java

The following Java program finds all perfect square numbers between two given numbers. The following program prints perfect numbers between 1 and 100. 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 square, we take the square root of the number and then convert it to an integer and then multiply the integer with itself. Then we check whether it is same as the given number.

// Finding perfect square numbers in a range using Java

public class SquareNumbersInRange {

    public static void main(String[] args) throws IOException {
        int starting_number = 1;
        int ending_number = 100;
        System.out.println("Perfect Numbers between "+starting_number+ " and "+ending_number);
        for (int i = starting_number; i <= ending_number; i++) {

            int number = i;

            int sqrt = (int) Math.sqrt(number);
            if (sqrt * sqrt == number) {
                System.out.println(number+ " = "+sqrt+"*"+sqrt);