Implement Sqrt function using binary search - The Coding Shala
Home >> Interview Questions >> Implement sqrt()
Implement Sqrt function using binary search
In this post, you will learn how to find the square root of a given number using the binary search algorithm. In java, the sqrt() function is already available to find square root for a number but in this post, we are going to implement sqrt() function using binary search.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
Sqrt function in Java
We can do this using a binary search. If we check one by one until reaching the target we might get time limit error for large numbers.
Other Posts You May Like
- Binary Search Algorithm
- Check if a given number is perfect square or not
- Median of two sorted arrays
- Rotate Array
- Longest Common Prefix