您的位置:首页 > 其它

LeetCode:Sqrt(x)

2013-12-12 20:07 363 查看
题目链接

Implement
int sqrt(int x)
.

Compute and return the square root of x.

面试时需要考虑x是否小于0.

分析:牛顿法,先假设一个初始解res(本文设为1),然后以抛物y = x^2-c(这里的c相当于题目中的x)上的点(res, res^2-c)为切点作切线,让res = 切线与x轴的交点,一直循环上面的操作直到前后两次的解相同。 本文地址

class Solution {
public:
int sqrt(int x) {
double res = 1.0, tmpres = 0.0;
while(int(res) - int(tmpres))
{
tmpres = res;
//res / 2.0 + x /(2.0 * res)为切线与x轴的交点
res =  res / 2.0 + x /(2.0 * res);
}
return (int)res;
}
};

对于评论中caichunli999提出的该方法的正确性证明如下:



这篇博客给出了14种求平方根解法:http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi

【版权声明】转载请注明出处/article/4879694.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: