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:
- Start with a range: low = 0, high = number
- Find the mid: (low + high) / 2
- If mid × mid is close to the number → mid is the square root
- If mid × mid is greater than the number → reduce the range
- Else → increase the range
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.
- Mid = 6.5 → 6.5² = 42.25 (too high)
- Mid = 6.25 → 6.25² = 39.06 (too low)
- Mid = 6.30 → 6.30² = 39.69 (too low)
- Mid = 6.32 → 6.32² = 39.93 (too low)
- Mid = 6.324 → 6.324² = 39.98 (almost there)
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:
- 0.01 → accuracy up to 2 decimals
- 0.0001 → accuracy up to 4 decimals
- 0.000001 → accuracy up to 6 decimals
Binary search guarantees fast and accurate results.
Practice Challenges
- Modify the program to print the steps of binary search as it narrows down the value.
- Write a function that calculates both floor and ceil square roots without using
Math.sqrt(). - Find square roots for all numbers from 1 to 100 and print them with 3 decimal precision.