FastPrepSquare Root with Newton Iteration

Square Root with Newton Iteration

Goldman Sachs logoGoldman Sachs● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a nonnegative real number x, return its nonnegative square root. Use Newton iteration.

A returned value is accepted when its absolute error is at most 10^-9 * max(1, sqrt(x)). Zero returns zero. Fractional square roots must be preserved.

Function

newtonSquareRoot(x: double) → double

Examples

Example 1

x = 2.0return = 1.4142135623730951

The square root of2 is approximately1.4142135623730951.

Example 2

x = 0.25return = 0.5

The fractional input0.25 has square root0.5.

Example 3

x = 0.0return = 0.0

Zero has square root zero.

Constraints

  • x = 0 or 10^-12 <= x <= 10^12.
  • Input and output use double-precision floating-point values.

More Goldman Sachs problems

See Goldman Sachs hiring insights
public double newtonSquareRoot(double x) {
    // Write your code here.
}
x2.0
expected1.4142135623730951
Checking account…