BSRC-P4

Integer square root

Practice 4 of 5Binary search11 tests

The problem

You are given a whole number n, which is 0 or more. Return the largest whole number r with r * r <= n. This is the square root of n, rounded down. Your answer must be exact, even for numbers much bigger than a float can store.

isqrt(16)          # 4
isqrt(17)          # 4
isqrt(10**30 - 1)  # 999999999999999

math.isqrt is switched off for this problem. Build it yourself with binary search.

Limits

  • n is 0 or more, with up to about 41 digits.
  • Return an int.

Builds on BSRC-5 Real-valued binary search and BSRC-6 Off-by-one traps.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1ZeroNot run
2OneNot run
3TwoNot run
4Just below a squareNot run
5A perfect squareNot run
6Just above a squareNot run
7A trillionNot run
8Floats get this one wrongNot run
9A 41-digit numberNot run
10Just past 2**53Not run
11A huge number that is not a squareNot run