Integer square root with no built-ins: binary search the answer, square the middle, and keep the largest value whose square still fits.
▼The problem
LeetCode 69 (Easy). Given a non-negative integer x (0 ≤ x ≤ 2³¹ − 1), return the square root of x rounded down to the nearest integer, without any built-in exponent function or operator (no pow(x, 0.5), no x ** 0.5, no sqrt).
Examples (LeetCode's): x = 4 → 2; x = 8 → 2 (the root is 2.83, rounded down).
The solution
def mySqrt(x):
lo, hi = 0, x
ans = 0
while lo <= hi:
mid = (lo + hi) // 2
if mid * mid <= x:
ans = mid # fits: record it
lo = mid + 1 # search higher
else:
hi = mid - 1 # search lower
return ansTranscript
Square Root of x. Given a non-negative whole number x, return its square root, rounded down. No built-in power or square root allowed. Picture x saplings: how wide is the biggest square orchard you can plant?
With four saplings, a two by two square uses every one, so the answer is two. With eight, three by three would need nine. The true root is about two point eight three, rounded down to two.
The slow way tries every width in turn: zero, one, two, three, until the next square needs more than x. That takes about square root of x checks. For the largest input, over two billion, it's forty-six thousand three hundred forty-one checks.
Here's the trick. The answer lies between zero and x, and the test flips only once. Small squares fit; once one is too big, every bigger square is too. So binary search the answer. Try the middle width. If mid times mid fits, the answer is at least mid: record it and search higher. If not, search lower.
Let's plant ninety-nine. Low is zero and high is ninety-nine, so mid is forty-nine, which needs over two thousand saplings. Too big. Twenty-four, then eleven: still too big. Five fits, so record it and search higher. Eight fits. Nine needs eighty-one: it fits too. Ten needs a hundred, one more than we have. Low passes high, so the answer is nine.
In code, low starts at zero and high at x. While low is at most high, take the middle. If its square is at most x, save it and move low past it. Otherwise, move high below it. With fixed-size integers, mid times mid can overflow, so compare mid with x divided by mid instead.
Each check halves the range, so the time is order log x. For the largest input, that's thirty-one checks, not forty-six thousand. Just a few variables, so the space is constant.
Search the answer, test the square, keep the last fit. That's Square Root of x.