69. Sqrt(x)

来源:互联网 发布:淘宝手机端的宝贝链接 编辑:程序博客网 时间:2024/06/14 04:03

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question
题目大意:二分查找,q*q <= x && (q + 1) * (q + 1) > x

class Solution {public:    int mySqrt(int x) {        unsigned long long tmp = 0;        unsigned long long tmp2 = 0;        unsigned long long  middle = 0, left = 0, right = x;        while(1){             middle = (left + right) / 2;             tmp = middle * middle;             tmp2 = (middle + 1) * (middle + 1);             if(tmp <= x && tmp2 > x)                break;             else if(tmp2 <= x)                left = middle + 1;             else if(tmp > x)                right = middle - 1;        }        return middle;    }};

思路二:牛顿法(好牛逼的样子而且速度比上面方法快)
《算法设计与分析基础》11.4中根据方程Xn+1 = 1/2(Xn + D/Xn), n = 0,1,…计算根号D, X0 = (1 + D)/2;
书中一个小例子:计算根号2,在第6位小数的地方对数字四舍五入
X0 = (1 + 2)/2 = 1.500000
X1 = (X0 + 2/X0)/2 = 1.416667
X2 = (X1 + 2/X1)/2 = 1.414216
X3 = (X2 + 2/X2)/2 = 1.414214
X4 = (X3 + 2/X3)/2 = 1.414214
这时候可以停下来,因为x4 = x3 = 1.414214

class Solution {public:    int mySqrt(int x) {        double D = (double)x;        double xi = (1 + D) / 2;        double delta = D - xi;        while(delta > 0.1){            double z = (xi + D / xi) / 2;            delta = xi - z;            xi = z;        }        return (int)xi;    }};
0 0