Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Code

class Solution:
    def mySqrt(self, x: int) -> int:
        if x < 2:
            return x
 
        y0 = x
        y1 = (y0 + x / y0) / 2
        while abs(y0 - y1) >= 1:
            y0 = y1
            y1 = (y0 + float(x) / y0) / 2
 
        return int(y1)

Explanation:

1. Problem Setup

We aim to compute the square root of a number , denoted . This can be formulated as solving the equation:

The solution to this equation satisfies .

2. Newton’s Method

Newton’s method is an iterative algorithm for finding roots of a differentiable function . The iteration formula is:

where:

  • is the current estimate of the root,
  • is the derivative of .

3. Applying to

For :

Substituting and into the formula:

Simplify:

This gives the iterative formula:

4. Initial Guess

The initial guess is chosen because lies between and for , making a reasonable starting point.