[LintCode]sqrt(x)

法1:二分

 1 class Solution {
 2 public:
 3     /**
 4      * @param x: An integer
 5      * @return: The sqrt of x
 6      */
 7     int sqrt(int x) {
 8         // write your code here
 9         long long l = 1, r = x;
10         while(l<r)
11         {
12             long long m = (l+r)/2;
13             if(m*m>x)   r = m-1;
14             else
15             {
16                 if((m+1)*(m+1)>x)   return m;
17                 else
18                 {
19                     l = m+1;
20                 }
21             }
22         }
23     }
24 };

 法2:牛顿法

要求x的平方根,首先任取一个数y,如果y不是x的平方根或者精度不够,则令y = (y+x/y)/2,循环直到获得x的平方根或者达到我们满意的精度为止,每次循环都会使y更接近x的平方根。

 1 #include <cmath>
 2 class Solution {
 3 public:
 4     /**
 5      * @param x: An integer
 6      * @return: The sqrt of x
 7      */
 8     int sqrt(int x) {
 9         // write your code here
10         double y = 1.0;
11         while(abs(y*y-x)>1)
12             y = (y+x/y)/2;
13         return (int)y;
14     }
15 };
原文地址:https://www.cnblogs.com/pczhou/p/4651713.html