codejump
EasyPythonJavaScriptTypeScript

Binary Search — Integer Square Root

AlgorithmsBinary SearchMath

solve(x) — return the square root of the non-negative integer x, rounded down
to an integer. Do not use Math.sqrt, **0.5 or any built-in root: binary search the
answer instead.

You are not searching an array, you are searching the range 0..x for the largest
r with r * r <= x. The predicate "r * r is small enough" is true then false, which
is exactly what binary search needs.

Examples

solve(4)           → 2
solve(8)           → 2
solve(0)           → 0
solve(2147395599)  → 46339

Sample tests

Test #1Perfect square
Input: [4]
Output: 2
Test #2Rounds down
Input: [8]
Output: 2
Test #3Zero
Input: [0]
Output: 0