Check Perfect Square in Java Without Using Math.sqrt() – Explanation, Logic, Examples, and Program

Learn how to check whether a number is a Perfect Square in Java without using Math.sqrt(). This guide explains the logic, provides examples, and includes an efficient program using iterative checking.

Check Perfect Square in Java Without Using Math.sqrt()

A Perfect Square is a number that can be expressed as the square of an integer. Usually, we check perfect squares using Math.sqrt(), but sometimes interviewers ask you to do it without using any square root function.


Approach Without Math.sqrt()

To determine whether a number is a perfect square without using Math.sqrt(), we can:

This method is simple, reliable, and often asked in interviews.


Example

Check if 36 is a Perfect Square

Since 6² = 36, the number 36 is a Perfect Square.


Java Program (Without Using Math.sqrt)


public class PerfectSquareWithoutSqrt {

    // Function to check perfect square without Math.sqrt()
    static boolean isPerfectSquare(int num) {
        if (num < 0) return false; // negative numbers are never perfect squares
        
        for (int i = 1; i * i <= num; i++) {
            if (i * i == num) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int num = 36;

        if (isPerfectSquare(num)) {
            System.out.println(num + " is a Perfect Square");
        } else {
            System.out.println(num + " is NOT a Perfect Square");
        }
    }
}

Why This Works

Instead of calculating the square root, we check every number starting from 1 and square it. As soon as the square exceeds the target number, the loop stops—making it efficient.

For example, if the number is 10000, the loop runs only up to 100 (its approximate root).


Practice Challenges

  1. Write a program to print all perfect squares between 1 and 1000 without using Math.sqrt().
  2. Create a function that returns the nearest perfect square for any given number.
  3. Given an array of numbers, print only those which are perfect squares (without using Math.sqrt()).