call(back)
Algorithms & Data StructureseasySign in to star problems

Square Root Without Math.sqrt

Write sqrt(x): the square root without Math.sqrt, Math.pow or ** 0.5 (in Python, without math.sqrt), accurate to 6 decimal places. A negative x gives NaN (float("nan") in Python).

sqrt(16)     // 4
sqrt(2)      // 1.414214
sqrt(0.25)   // 0.5

The grader switches off the built-in root functions and compares results to 6 decimal places.

Hints

Hint 1

Binary-search between 0 and max(1, x). The max matters for x < 1, whose root is larger than x.

Hint 2

Loop a fixed number of times rather than while (hi - lo > epsilon), which never ends for large inputs.

Asked at