50 XP

60. Integer square root

Intermediate searching math

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.
  • n can be over a million million, so trying 1, 2, 3, ... one at a time is far too slow.

Example 1

Inputn = 17
Output4
Explanation4 * 4 = 16 fits; 5 * 5 = 25 is too big.

Example 2

Inputn = 16
Output4
ExplanationA perfect square: 4 * 4 is exactly 16.

Example 3

Inputn = 0
Output0
Explanation0 * 0 = 0.

Constraints

  • n is 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).

Code
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