Integer Square Root with Newton's Method and No Library Calls
Company: Goldman Sachs
Role: Quantitative Researcher
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Implement a square-root routine based on Newton's method that returns the integer square root of a non-negative 32-bit integer, the largest value whose square does not exceed the input, without calling library square-root or power functions. It tests numerical iteration, termination conditions and exact integer arithmetic.
Read the full Goldman Sachs Quantitative Researcher interview experience this question came from
Constraints
- 0 <= x <= 2^31 - 1
- The answer is at most 46340, but squaring a value just above it exceeds 2^31 - 1 (46341 × 46341 = 2147488281); fixed-width languages need 64-bit intermediate arithmetic.
- Compute the root with Newton's method; do not call a library routine that computes square roots, powers or logarithms (such as math.sqrt, math.isqrt, math.pow, math.log or x ** 0.5).
Examples
Input: (0,)
Expected Output: 0
Explanation: Minimum valid input: 0 * 0 = 0, so the root of 0 is 0 (an implementation must not divide by zero).
Input: (1,)
Expected Output: 1
Explanation: Root equals the input: 1 * 1 = 1 <= 1 and 2 * 2 = 4 > 1; catches a search capped at x / 2.
Hints
- The answer r is the unique non-negative integer with r * r <= x < (r + 1) * (r + 1).
- The interviewer asked for Newton's method: think about how to refine a guess for the root using only integer arithmetic, and about a stopping rule that cannot loop forever.
- Squares of values near 46341, and sums near 2^31, exceed the signed 32-bit range; in Java and C++ keep intermediate arithmetic in a wider type.