Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

 

Code:

class Solution {
public:
    int sqrt(int x) {
        int start=0;
        int end=x/2>std::sqrt(INT_MAX)?std::sqrt(INT_MAX):x/2+1;
        while(start<=end){
            int mid=(start+end)/2;
            if(x==mid*mid)
                return mid;
            else if(mid*mid<x)
                start=mid+1;
            else
                end=mid-1;
        }
        return (start+end)/2;
    }
};

 

Analysis:
According to Newton's Method(http://en.wikipedia.org/wiki/Newton's_method), we can use
 x_(k+1)=1/2(x_k+n/(x_k))
to get the sqrt(x).

class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (x==0) {return 0;}
        if (x==1) {return 1;}
       
        double x0 = 1;
        double x1;
        while (true){
            x1 = (x0+ x/x0)/2;
            if (abs(x1-x0)<1){return x1;}
            x0=x1;
        }
         
    }
};

 

posted @ 2013-11-08 17:17  WinsCoder  阅读(149)  评论(0编辑  收藏  举报