[leetcode] 【分治法】 69. Sqrt(x)
来源:互联网 发布:苹果cms定时任务采集 编辑:程序博客网 时间:2024/06/06 09:50
Implement int sqrt(int x)
.
Compute and return the square root of x.
题意
实现平方根函数,返回x的根。
题解
二分法,取到合适的数为止。
class Solution {public: int mySqrt(int x) { if(x<2) return x; double begin=0,end=x,mid=1,res=0; while(abs(res-x)>0.000001) { mid=(begin+end)/2; res=mid*mid; if(res>x) end=mid; else begin=mid; } return (int)mid; }};牛顿迭代法(我没有用这个方法,这题主要练练二分法):
牛顿迭代法(Newton's method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。
以下代码cur = pre/2 + x/(2*pre)是化简计算的结果。。这里的f(x) = x^2-n
class Solution {public: int mySqrt(int x) { double pre = 0; double cur = x; // 这里从x开始 从x/2开始会导致 1 不能满足 x(n+1)= xn - f'(xn)/f(xn) while(abs(cur - pre) > 0.000001){ pre = cur; cur = (pre/2 + x/(2*pre)); } return int(cur); }};
0 0
- [leetcode] 【分治法】 69. Sqrt(x)
- 69. Sqrt(x)(分治)
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- [leetcode] 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode-69. Sqrt(x)
- 差值器大全
- 转置矩阵的分块并行乘法(C语言实现),计算矩阵C[rawn][rawn]=A[rawm][rawn]'*B[rawm][rawn],子块大小为S*T,其算法实现原理参加本代码的附件。
- redis配置文件配置详解
- Error:(25, 13) Failed to resolve: com.google.firebase:firebase-core:9.0.2
- ContentProvider 被访问的(一)
- [leetcode] 【分治法】 69. Sqrt(x)
- Top 10 Ways to Perfect Your Daily Routine with the Power of Science
- Redis作者:深度剖析Redis持久化
- 变态跳台阶
- 网络视频监控系统开发系列------数字视频技术概述
- Android四大组件之Activity
- java学习总结
- ContentProvider之访问者(二)
- mac ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)