Leetcode Sqrt(x)

参考Babylonian method

x_0 \approx \sqrt{S}. (x0  越接*S的*方根越好)

x_{n+1} = \frac{1}{2} \left(x_n + \frac{S}{x_n}\right),

\sqrt S = \lim_{n \to \infty} x_n.

class Solution {
public:
    int sqrt(double x) {
        if(x == 0) return 0;
        double root = x/2, tolerance = 1.0e-2;
        do{
            root=(root+x/root)/2;
        }while(abs(root*root-x)>tolerance);
        return root;
    }
};

这题感觉题目有问题,返回的*方根竟然是整数,

另一种方法是是用二分搜索

class Solution {
public:
    int sqrt(int x) {
        if(x < 2) return x;
        int left = 0, right = x;
        while(left <= right){
            int mid = (right+left)/2;
            if(mid < x/mid) left = mid+1;
            else if(x/mid < mid ) right = mid-1;
            else  return mid;
        }
        return right;
    }
};

如果题目要求的时浮点数可以考虑利用浮点数二分搜索

posted @ 2014-06-29 17:30  OpenSoucre  阅读(198)  评论(0编辑  收藏  举报