60. Integer square root
The integer square root of a whole number n is the largest whole number r with r * r <= n. For 17 it is 4,
since 4 4 = 16 fits and 5 5 = 25 doesn't.
Write a function isqrt(n) that takes a whole number n and returns its integer square root, without math.sqrt,
math.isqrt, ** 0.5 or pow(). The aim is the method: binary search, not over a list this time, but over the
possible answers.
- The answer for a perfect square is exact: 16 gives 4.
- 0 gives 0 and 1 gives 1.
ncan be over a million million, so trying 1, 2, 3, ... one at a time is far too slow.
Example 1
n = 174Example 2
n = 164Example 3
n = 00Constraints
nis a whole number from 0 to 2^53 - 1 (9,007,199,254,740,991).
Submit also runs 10 more tests you can't see.
Practises While Loops (lesson 14).
- The answer is somewhere from 0 to
n. Keep the range aslow = 0andhigh = n, and look at its middle,mid = (low + high) // 2. - If
mid * mid <= n, thenmidfits: remember it as the best so far, and look for a bigger one withlow = mid + 1. Otherwise it is too big:high = mid - 1. - Loop
while low <= high. Each step halves the range, so even 2^53 takes about 53 steps.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def isqrt(n):
"""Find the integer square root of n.
n: int, 0 or more
Returns: int, the largest r with r * r <= n
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.