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.
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
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log n) | The guess range halves. |
| Memory | O(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