Square Root Function
Problem statement
Write a function that returns the square root of a number x.
You can use the four basic operations: add, subtract, multiply and divide. Do not call a built-in square root or power function. The tests check only the returned value, so they cannot catch a built-in call. Keeping to this rule is up to you.
An answer is accepted when its distance from the true square root is at most 10^-6 * max(1, root). So the allowed error is 10^-6 when the root is at most 1, and 10^-6 times the root when the root is above 1.
Interview follow-up
This follow-up came up in the interview. It is not part of the judged function, and the editorial covers it.
- What if we are sure that the input number is an integer?
Function
squareRoot(x: double) → doubleExamples
Example 1
x = 2.0return = 1.41421356237309511.4142135623730951 * 1.4142135623730951 is about 2. The root is above 1, so the allowed error here is 10^-6 times the root, about 1.4 * 10^-6.
Example 2
x = 0.25return = 0.50.5 * 0.5 = 0.25. The root is larger than the input here, so a search for the root cannot stop at x.
Example 3
x = 16.0return = 4.04 * 4 = 16, so this integer input has an exact root.
Constraints
x = 0or10^-6 <= x <= 10^12xand the result are double-precision numbers.