实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842…,
由于返回类型是整数,小数部分将被舍去。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
牛顿迭代法:
Γ
(
x
2
)
=
0
\Gamma(x^2)=0
Γ(x2)=0
f
(
x
)
=
x
2
−
n
f(x)=x^2-n
f(x)=x2−n
求斜率:
2
x
2x
2x
x
−
(
x
2
−
n
)
/
2
x
=
x
/
2
+
n
/
2
x
x-(x^2-n)/2x=x/2+n/2x
x−(x2−n)/2x=x/2+n/2x
x
n
+
1
=
x
n
/
2
+
n
/
2
x
n
x_{n+1}=x_{n}/2+n/2x_n
xn+1=xn/2+n/2xn
最后进行迭代;
递归解决:
class Solution {
public:
int mySqrt(int x) {
//递归解决;
if(x==1||x==0){
return x;
}
return Sqrt(x,x);
}
double Sqrt(double x, int n){
double res = x/2+n/(2*x);
if(res==x){
return x;
}else{
return Sqrt(res, n);
}
}
};
2、迭代法:
class Solution {
public:
int mySqrt(int x) {
//迭代解决;
if(x==1||x==0){
return x;
}
int n = x;
double now = 0;
double res = 1;
while(res!=now){
now = res;
res = res/2+x/(2*res);
}
return int(res);
}
};
3、还可以用二分查找:
class Solution {
public:
int mySqrt(int x) {
//二分查找;
if(x==0||x==1){
return x;
}
int l=0,r=x;
int ans=-1;
while(l<=r){
int mid = l+((r-l)>>2);
if((long long)mid*mid<=x){
ans = mid;
l = mid+1;
}else{
r = mid-1;
}
}
return int(ans);
}
};