Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 69] Sqrt(x)

Question

link

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.

求出根号a的近似值:首先随便猜一个近似值x,然后不断令x等于x和a/x的平均数,迭代个六七次后x的值就已经相当精确了。
例如,我想求根号2等于多少。假如我猜测的结果为4,虽然错的离谱,但你可以看到使用牛顿迭代法后这个值很快就趋近于根号2了:
(       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..
.... \
这种算法的原理很简单,我们仅仅是不断用(x,f(x))的切线来逼近方程x^2-a=0的根。根号a实际上就是x^2-a=0的一个正实根,这个函数的导数是2x。也就是说,函数上任一点(x,f(x))处的切线斜率是2x。那么,x-f(x)/(2x)就是一个比x更接近的近似值。代入 f(x)=x^2-a得到x-(x^2-a)/(2x),也就是(x+a/x)/2。

相关的代码如下:

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;
}