1、题目描述
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
2、示例
输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
3、题解
基本思想:牛顿迭代法求平方根,迭代公式Xn+1=(Xn^2+N)/2Xn=(Xn+N/Xn)/2,初始Xn可以设置为N或者N/2,初始Xn设置为N/2时要考虑特殊情况1。

同理可得:牛顿迭代法求立方根,迭代公式为Xn+1=(2Xn^3+N)/3Xn^2=(2Xn+N/Xn^2)/3
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int mySqrt(int x) {
//基本思想:牛顿迭代法求平方根,迭代公式Xn+1=(Xn^2+N)/2Xn=(Xn+N/Xn)/2,初始Xn可以设置为N或者N/2
//初始Xn设置为N/2时要考虑特殊情况1
if (x == 1)
return 1;
//防止求root*root时溢出,用long long
long long root = x / 2;
//精度只要满足1即可
while (root * root - x >= 1)
{
root = (root + x / root) / 2;
}
return root;
}
int CubeRoot(int x) {
long long root = 100000;
if (x < root) {
root=100;
}
while (root*root*root - x >= 1)
{
root = (2*root + x/(root*root))/3;
}
return root;
}
};
int main()
{
Solution solute;
int x = 2147395599;
cout << solute.mySqrt(x) << endl;
return 0;
}
本文介绍了一种使用牛顿迭代法计算非负整数平方根的方法,并提供了C++代码实现。通过迭代公式Xn+1=(Xn+N/Xn)/2,从N/2开始迭代直至满足精度要求,特别处理了输入为1的情况。
2万+

被折叠的 条评论
为什么被折叠?



