# [LeetCode 69] Sqrt(x)

### Question

Implement `int sqrt(int x)`.

Compute and return the square root of x.

### Stats

 Frequency 4 Difficulty 4 Adjusted Difficulty 4 Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

### Analysis

This is a classic question of math and CS. It’s easy, but there are a few magical solutions for this problem.

### Solution

The most standard solution is using binary search. I have the code for that.

Newton’s method is a great way to solve this problem. It uses derivative to keep finding the next better approximation to the root of the value. There is a great article on this topic talking about Newton’s method, and some even faster implementations.

That article is definitely worth reading. I will quote a small propertion of it.

(       4  + 2/4        ) / 2 = 2.25
(     2.25 + 2/2.25     ) / 2 = 1.56944..
( 1.56944..+ 2/1.56944..) / 2 = 1.42189..
( 1.42189..+ 2/1.42189..) / 2 = 1.41423..
....

float SqrtByNewton(float x)
{
float val = x;//最终
float last;//保存上一个计算的值
do
{
last = val;
val =(val + x/val) / 2;
}while(abs(val-last) > eps);
return val;
}然后我们再来看下性能测试：

### My code

Binary search.

``````public int sqrt(int x) {
if (x <= 1)
return x;
long left = 1, right = x;
long mid, square;
while (right - left > 1) {
mid = (left + right) / 2;
square = mid * mid;
if (square == x)
return (int) mid;
else if (square > x)
right = mid;
else if (square < x)
left = mid;
}
return (int) left;
}
``````

Newton’s method, code from this blog.

``````public int sqrt(int x) {
if (x == 0) return 0;
double last = 0, res = 1;
while (res != last) {
last = res;
res = (res + x / res) / 2;
}
return (int) res;
}
``````