Python coding

Integer square root

Given a non-negative integer x, return its square root rounded down: the largest integer r with r * r <= x. For example, 8 gives 2, because 2 * 2 <= 8 but 3 * 3 > 8.

Use integer arithmetic only: no math.sqrt, math.isqrt or ** 0.5, since the search is the exercise. Constraints: 0 <= x <= 10^15. Aim for O(log x).

Besides the tests, one large input (x around 4 · 10^13) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • floor_sqrt(8) → 2
  • floor_sqrt(16) → 4
  • floor_sqrt(26) → 5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

r * r <= x holds for small r and fails from some point on. A monotonic yes/no question means you can binary search the answer instead of counting up to it.

Hint 2

Search [0, x + 1] for the first r with r * r > x: if mid * mid > x keep hi = mid, else lo = mid + 1. The answer is lo - 1.

Hint 3

Try x = 0 and x = 1: the first square above them is at r = x + 1, so a search that starts with hi = x never reaches it.

Solution and why it works
pythonO(log x) · O(1)
def floor_sqrt(x: int) -> int:
    lo, hi = 0, x + 1                # the first r with r * r > x is in [0, x + 1]
    while lo < hi:
        mid = (lo + hi) // 2
        if mid * mid > x:
            hi = mid
        else:
            lo = mid + 1
    return lo - 1                    # the last r with r * r <= x

Squares only grow, so r * r > x reads false, false, …, true as r rises: binary search finds the first true in about 50 halvings for x up to 10^15, and the answer is the value just before it. Counting up from 0 takes √x steps, ~32 million at the top of the range. Floats are the other trap, worth knowing in an interview: past 2^52, int(x ** 0.5) can round up, as it does for x = 94906265² − 1.

Related lab: Loops in motion