Sqrt(x)
Find the square root of a whole number, rounded down, without a square root function.
Given a non-negative integer xMath.sqrtMath.pow
Example 1
Output: 2
Example 2
Output: 2
Explanation: the square root of 8 is 2.828..., and rounded down it is 2.
The Idea
Think of x as a pile of tiles. The square root asks how long the side of a square made from those tiles can be. With 4 tiles you can lay a 2 by 2 square and use them all. With 8 tiles, a 2 by 2 square uses 4 of them, and a 3 by 3 square would need 9, one more than you have. So the answer for 8 is 2, with 4 tiles left over.
Put that way, the answer is the largest whole number r whose square, r × r, is at most x. No decimals are needed: we only ever multiply whole numbers and compare the result with x.
Which r should we try, though? Look at the picture below, made for x = 8. The top row holds every candidate r from 0 to 8, and under each one is its square. The row labelled "test" says whether that square fits, meaning it is at most 8, or is too big.
The test row reads fits, fits, fits, and then too big all the way to the end. Squares only grow as r grows, so once one square is too big, every square after it is too big as well. The row switches from fits to too big exactly once, at the dashed line, and the answer is the last r before it: 2.
A row that switches only once can be searched by halving, the way you find a word in a dictionary. Guess the middle, and the test tells you which half to keep. In the row labelled "guess", the first guess is 4, the middle of 0 to 8. Its square, 16, is too big, so the answer is below 4. The guesses 1 and 2 fit, so the answer is at least 2. The last guess, 3, is too big, and nothing is left between 2 and 3. Searching by halving like this is called binary search.
Solution Approach
Turning that idea into code means settling three things: which range to search, how to remember the best r found so far, and how to square a number without overflow.
The range to search
Where can the answer lie? It is never below 0, and never above x, because for any r bigger than x, r × r is bigger than x too. So the search keeps two ends, lohi
The simple way is to try r = 0, 1, 2, ... until a square is too big. That takes about √x steps, over 46,000 for the largest Java intint
Remembering the last r that fits
What happens after each guess? The guess is the middle of the range, midmidmidmidmidanswerlo = mid + 1midhi = mid - 1
The search stops when lohianswer
Squaring without overflow
Can the square itself go wrong? When x is near that largest intintint(long) mid * midlong
For the same reason the middle is computed as lo + (hi - lo) / 2(lo + hi) / 2
Newton's method, a faster option
Is there a quicker way? Newton's method starts with r = x and, while r × r is too big, replaces r with (r + x / r) / 2
Java Solution
The method mySqrt
- First, set up the range with
andlo = 0 , and a variablehi = x for the last r that fits.answer = 0 - Loop while
. In each pass, pick the middle of the range aslo <= hi .mid = lo + (hi - lo) / 2 - Square
as amid and compare it withlong . If it fits, savex inmid and moveanswer tolo . If it is too big, movemid + 1 tohi .mid - 1 - When the loop ends, return
.answer
The mainint
public class Sqrt {
// Largest r with r * r <= x
public static int mySqrt(int x) {
int lo = 0;
int hi = x;
int answer = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long) mid * mid <= x) { // long: mid * mid can overflow an int
answer = mid; // mid fits; look for a larger one
lo = mid + 1;
} else {
hi = mid - 1; // mid is too big
}
}
return answer;
}
public static void main(String[] args) {
int[] inputs = {4, 8, 0, 1, 15, 16, 2147395599, 2147483647};
for (int x : inputs) {
System.out.println("mySqrt(" + x + ") = " + mySqrt(x));
}
}
}
Running it prints:
mySqrt(4) = 2
mySqrt(8) = 2
mySqrt(0) = 0
mySqrt(1) = 1
mySqrt(15) = 3
mySqrt(16) = 4
mySqrt(2147395599) = 46339
mySqrt(2147483647) = 46340
For x = 8 the loop makes the four guesses from the picture, 4, 1, 2 and 3, and returns 2, the value saved at the third guess. The lines for 15 and 16 show the rounding down: 3 × 3 = 9 fits under 15 but 4 × 4 = 16 does not, while 16 is a perfect square and gets exactly 4.
The last two lines are where the longmid * midintlong
The original implementation,
Complexity
The work is one binary search over the candidates 0 to x, with one multiplication and one comparison per guess.
- Time: O(log x), because each guess halves the range from 0 to x, so even x = 2,147,483,647 needs only 31 guesses.
- Space: O(1), because the search keeps only
,lo ,hi andmid , however large x is.answer
The same search answers whether a number is a perfect square in