Find Square Root of a Number in Java Without Using Math.sqrt() – Explanation, Logic, Examples, and Program

Learn how to calculate the square root of any number in Java without using Math.sqrt(). This guide explains the binary search method, includes examples, and provides a clean Java program.

Find Square Root of a Number in Java Without Using Math.sqrt()

The square root of a number is a value which, when multiplied by itself, gives the original number. In Java, we normally use the built-in Math.sqrt() function — but interviewers often ask you to implement your own logic without using it.

A powerful and efficient way to do this is by using the Binary Search Method, which works for both perfect squares and non-perfect squares.


Binary Search Approach

Binary search helps us approximate the square root by repeatedly narrowing the range of possible answers.

Steps:

We continue until we reach the required precision, such as 3, 4, or 5 decimal places.


Example

Find √40 (up to 3 decimal places)

40 lies between 36 (6²) and 49 (7²), so √40 is between 6 and 7.

So, the approximate square root of 40 is around 6.324.


Java Program (Binary Search Method)


public class SquareRootWithoutSqrt {

    // Function to find square root with binary search
    static double squareRoot(double num, double precision) {
        double low = 0;
        double high = num;
        double mid = 0;

        // Binary search for integer part
        while (high - low > precision) {
            mid = (low + high) / 2;

            if (mid * mid > num) {
                high = mid;
            } else {
                low = mid;
            }
        }

        return (low + high) / 2;
    }

    public static void main(String[] args) {
        double num = 40;
        double precision = 0.0001; // 4 decimal places

        double result = squareRoot(num, precision);
        System.out.println("Square root of " + num + " is: " + result);
    }
}

How Accurate Is This?

The precision value determines how close the result is to the actual square root. For example:

Binary search guarantees fast and accurate results.


Practice Challenges

  1. Modify the program to print the steps of binary search as it narrows down the value.
  2. Write a function that calculates both floor and ceil square roots without using Math.sqrt().
  3. Find square roots for all numbers from 1 to 100 and print them with 3 decimal precision.