[LeetCode] Sqrt

本文介绍使用牛顿法计算平方根的方法,并给出了详细的迭代过程。通过简单的初始猜测,逐步逼近精确解,最终实现对任意正数求平方根。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Problem]

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的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值