Advanced · Searching · 199 of 264
Integer square root
Find the largest whole number r with r * r <= n using binary search (no ** 0.5, no math functions). n can be huge.
Input: a whole number n (0 or more, up to 10^30). Output: r
Examples
Input
17
Output
4
Input
0
Output
0
Input
16
Output
4
2 more tests check other inputs when you press Check.
Stuck? The idea behind searching
Linear search looks at each item in turn. Binary search works on a sorted list: look at the middle, then throw away the half that can't hold the answer.
Binary search finds an item among a million in about 20 steps.
def find(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Watch for: lo = mid instead of mid + 1 can loop for ever when two items are left.