Divide & Conquer · Binary search

Integer Square Root Visualizer

What is Integer Square Root

Return the greatest integer whose square is still at most n. Search that integer between 0 and n. A floating-point square root can be off by one on the largest tests, so compare mid squared with n using integers.

10
3

Approach

The integer square root is the greatest integer whose square is still at most n. The answers from 0 through n are ordered, so binary search can hunt for that greatest value.

Square fitsmid * mid <= n. Remember mid, then try a larger guess by moving lo to mid + 1.
Square is too bigEvery integer above mid is also too big. Set hi to mid - 1.

The search uses integer multiplication, so it stays exact even when n has 18 digits. The picture caps the number line so the shrinking window stays readable.

Interactive solution

lo, mid, and hi shrinking on the number line
lo, hi, ans = 0, n, 0
while lo <= hi:
mid = (lo + hi) // 2
if mid * mid <= n: ans = mid; lo = mid + 1
else: hi = mid - 1
return ans
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(log n)The guess range halves.
MemoryO(1)Only lo, hi, mid, and the best guess are stored.

Implementation

def isqrt(n):
    lo, hi, ans = 0, n, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        if mid * mid <= n:
            ans = mid
            lo = mid + 1
        else:
            hi = mid - 1
    return ans