> For the complete documentation index, see [llms.txt](https://aaronice.gitbook.io/lintcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aaronice.gitbook.io/lintcode/mathematics/sqrt_x.md).

# Sqrt(x)

Implement`int sqrt(int x)`.

Compute and return the square root of*x*, where *x* is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

**Example 1:**

```
Input:
 4

Output:
 2
```

**Example 2:**

```
Input:
 8

Output:
 2

Explanation:
 The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
```

## Analysis

### Binary Search

Typical binary search problem (although better way could be Newton's method)

Tips:

use `mid == x / mid` to avoid overflow

`right` is the closest, since before the last loop, it was left = mid = right

**Newton**

\[\[<https://en.wikipedia.org/wiki/Newton's_method](https://en.wikipedia.org/wiki/Newton's_method](https://en.wikipedia.org/wiki/Newton's_method]%28https://en.wikipedia.org/wiki/Newton's_method)\\>)

`x_(n+1) = x_(n) - f(x_n) / f'(x_(n))`

For the sqrt(x) function, it's actually:

`f(x) = x^2 - y`

`f'(x) = 2 * x`

Then `x(n+1) = x(n) - [x(n) ^ 2 - y] / [2 * x(n)]`

Simplified:

`x(n+1) = [x(n) + y / x(n)] / 2`

```java
    public int mySqrt(int x) {
        long r = x;
        while (r*r > x)
            r = (r + x/r) / 2;
        return (int) r;
    }
```

## Solution

Using binary search basic template #1

Source: <https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution/24042>

* The sequence`1, 2, ... , n`has no duplication.
* Near the very end, closest step, before`while`loop,`left = mid = right`.
* In`while`, If`mid < sqrt(x)`,`left = mid + 1`executed,`right`pointer is not moving, and`right`is the answer.
* If`while`, If`mid > sqrt(x)`,`right = mid - 1`executed,`right`pointer shifts left`1`, closest to`sqrt(x)`,`right`is also the answer.

```java
public int mySqrt(int x) {
    int left = 1, right = x;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (mid == x / mid) {
            return mid;
        } else if (mid < x / mid) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return right;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/mathematics/sqrt_x.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
