LeetCode:Sqrt(x)
2013-12-12 20:07
363 查看
题目链接
Implement
Compute and return the square root of x.
面试时需要考虑x是否小于0.
分析:牛顿法,先假设一个初始解res(本文设为1),然后以抛物y = x^2-c(这里的c相当于题目中的x)上的点(res, res^2-c)为切点作切线,让res = 切线与x轴的交点,一直循环上面的操作直到前后两次的解相同。 本文地址
对于评论中caichunli999提出的该方法的正确性证明如下:
这篇博客给出了14种求平方根解法:http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi
【版权声明】转载请注明出处:/article/4879694.html
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
相关文章推荐
- jQuery三级联动
- 手游团队的六个死因 取舍Unity技术引争议
- C++里的static成员变量
- 线程池python
- kmp和扩展kmp原理
- UFLDL Tutorial_Building Deep Networks for Classification
- 复杂的表单服务器端验证
- jQuery对Ajax的封装:load(),get(),post()
- [web前端笔试] AJAX笔试面试题汇总
- Java提供的enum详解
- JQuery判断元素是否存在
- hdu1054 二分图水题
- effective C++: 8.定制new和delete
- MFC Cstring ,double 互换
- 复杂的表单客户端验证
- 新蒂下午茶体基本版SentyTEA-Basic
- 查看Oracle数据库中未绑定变量的SQL
- hibernate hbm.xml配置映射
- 新蒂下午茶体基本版SentyTEA-Basic
- Android Info类