[LeetCode] Sqrt
来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/05/17 22:13
[Problem]
[Analysis]
牛顿方法,对于sqrt(S),随便猜一个x (1 <= x <=S),则sqrt(S) = x + e,其中e为误差。
第一次迭代:
sqrt(S) =x_1 + e
S = (x_1 +e)^2
S = x_1^2 +2ex_1 + e^2
e = (S -x_1^2) / (2x_1 + e)
相比于x,假设e非常小,则
e ≈ (S -x_1^2) / 2x_1
第二次迭代:
x_2 ≈ x_1 +e
= x_1 + (S - x_1^2) / 2x_1
= (x_1 + S/x_1)/2
第n+1次迭代:
x_(n+1) ≈x_n + e
= x_n + (S- x_n^2) / 2x_n
= (x_n +S/x_n)/2
更多方法可以参考:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Approximations_that_depend_on_IEEE_representation
http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi
[Solution]
说明:版权所有,转载请注明出处。Coder007的博客
Implement int sqrt(int x)
.
Compute and return the square root of x.
[Analysis]
牛顿方法,对于sqrt(S),随便猜一个x (1 <= x <=S),则sqrt(S) = x + e,其中e为误差。
第一次迭代:
sqrt(S) =x_1 + e
S = (x_1 +e)^2
S = x_1^2 +2ex_1 + e^2
e = (S -x_1^2) / (2x_1 + e)
相比于x,假设e非常小,则
e ≈ (S -x_1^2) / 2x_1
第二次迭代:
x_2 ≈ x_1 +e
= x_1 + (S - x_1^2) / 2x_1
= (x_1 + S/x_1)/2
第n+1次迭代:
x_(n+1) ≈x_n + e
= x_n + (S- x_n^2) / 2x_n
= (x_n +S/x_n)/2
更多方法可以参考:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Approximations_that_depend_on_IEEE_representation
http://www.codeproject.com/Articles/69941/Best-Square-Root-Method-Algorithm-Function-Precisi
[Solution]
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;
}
// iterative
double pre = 1.0;
double res = (double)x;
while(res - pre){
pre = res;
res = 0.5*(res + x/res);
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
阅读全文
0 0
- Leetcode: sqrt
- leetcode sqrt
- Leetcode-sqrt
- 【leetcode】sqrt
- [LeetCode] Sqrt
- Leetcode : Sqrt
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [leetcode] sqrt(int num)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [LeetCode] Surrounded Regions
- httpurlconnnection_newstop
- [LeetCode] Word Search
- [LeetCode] String to Integer(atoi)
- [LeetCode] Sort Colors
- [LeetCode] Sqrt
- 图的存储(前向星)
- [LeetCode] Simplify Path
- 《高性能SQL调优精要与案例解析》一书谈SQL调优(SQL TUNING或SQL优化)学习
- [LeetCode] N-Queens
- [LeetCode] N-Queens II
- [LeetCode] Restore IP Addresses
- RecyclerView和购物车选择模式
- [LeetCode] Maximal Rectangle