Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Integer square root without a library

Easy · Target 10 minutes · Binary search · Type asked atMicrosoftBloomberg

Given a non-negative integer x, return ⌊√x⌋, the largest integer whose square is at most x. Do not use a square-root function or exponentiation from a library.

Examples

InputOutputWhy
x = 822² = 4 ≤ 8 < 9 = 3².
x = 164
x = 21474836474634046340² = 2,147,395,600; 46341² overflows a 32-bit integer.

Constraints

  • 0 ≤ x ≤ 2³¹ − 1

Hints

Hint 1

The test "r² ≤ x" is true for r = 0, 1, 2, … up to some point, then false for ever. You want the last true.

Hint 2

Search r in [0, x]. When the test passes, mid could be the answer, so keep it: lo = mid. Which way must mid round to avoid an infinite loop?

Hint 3

mid² for mid near 2³¹ does not fit in 32 bits. Use 64-bit arithmetic, or compare mid with x / mid.

Where people lose marks

  • Rounding mid down while setting lo = mid: with lo = 3, hi = 4 the loop spins on mid = 3 for ever.
  • Computing mid * mid in 32 bits.
  • Starting hi at x / 2 and forgetting x = 1, whose root is 1.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.