Sqrt(x)

Find the square root of a whole number, rounded down, without a square root function.

Given a non-negative integer x, return its square root rounded down to a whole number. Built-in helpers such as Math.sqrt or Math.pow are not allowed.

Example 1
Input: x = 4
Output: 2
Example 2
Input: x = 8
Output: 2
Explanation: the square root of 8 is 2.828..., and rounded down it is 2.
Solution

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.

For x = 8, the candidates r = 0 to 8 and their squares 0, 1, 4, 9, 16 and so on. r = 0, 1 and 2 fit, r = 3 to 8 are too big, so the answer is 2. The guesses, in order, are 4, 1, 2 and 3.

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, lo starting at 0 and hi starting at x, and the answer is always between them.

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 int, 2,147,483,647. Halving the range needs at most 31 guesses for any int, because 31 halvings shrink about 2 billion candidates to one.

Remembering the last r that fits

What happens after each guess? The guess is the middle of the range, mid. If mid × mid fits, mid could be the answer, but a larger r might fit too. So the code saves mid in a variable answer and keeps searching above it, with lo = mid + 1. If the square is too big, the answer is below mid, so hi = mid - 1.

The search stops when lo passes hi and no candidates are left. The last guess may have been too big, as 3 was for x = 8, so the answer is not the last guess but the last saved one, which answer holds.

Squaring without overflow

Can the square itself go wrong? When x is near that largest int, 2,147,483,647, the first guess is over a billion, and its square is far too big for an int. An int result that goes past its largest value wraps around and comes out wrong, for example 65,536 × 65,536 gives 0. This is called overflow. Writing (long) mid * mid makes Java multiply in long, which holds values up to about 9.2 × 1018, so the square is always exact.

For the same reason the middle is computed as lo + (hi - lo) / 2. The shorter (lo + hi) / 2 adds the two ends first, and that sum can overflow when both are large.

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, the average of r and x / r. For x = 2,147,483,647 it reaches 46,340 in 19 rounds, against 31 guesses for binary search. Binary search is still the easier one to get right and to prove correct, so it is the one used here.

Java Solution

The method mySqrt works in these steps:

  1. First, set up the range with lo = 0 and hi = x, and a variable answer = 0 for the last r that fits.
  2. Loop while lo <= hi. In each pass, pick the middle of the range as mid = lo + (hi - lo) / 2.
  3. Square mid as a long and compare it with x. If it fits, save mid in answer and move lo to mid + 1. If it is too big, move hi to mid - 1.
  4. When the loop ends, return answer.

The main method runs both examples, the smallest inputs 0 and 1, the numbers 15 and 16 on either side of a perfect square, and two inputs near the top of the int range.

Java
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:

Output
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 long square matters. 46,340 × 46,340 is 2,147,395,600, one more than 2,147,395,599, so that input gets 46,339 and the next one up gets 46,340. With mid * mid computed as an int instead, the wrapped squares mislead the search: x = 2,147,395,599 comes back as 2,147,395,599 itself, and for x = 2,147,483,647 the loop was still running after 1,000 passes. The long version needs 31 passes for each.

The original implementation, Sqrt.java, is on GitHub.

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, mid and answer, however large x is.

The same search answers whether a number is a perfect square in Valid Perfect Square.