题目
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
思路
即求
r
e
s
∗
r
e
s
<
=
x
a
n
d
(
r
e
s
+
1
)
∗
(
r
e
s
+
1
)
>
x
res*res<=x \ and \ (res+1)*(res+1)>x
res∗res<=x and (res+1)∗(res+1)>x。
可以在整数范围内二分,但还有另一种牛顿逼近法。
牛顿法
https://www.zhihu.com/question/20690553
http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html
这两篇讲的很清楚,思想是近似一个曲线的根(与x轴的交点),可以在曲线上一点做切线,切线与x轴交点向曲线做垂线,得到迭代后的新点。
切线方程:
f
(
x
)
=
f
(
x
i
)
+
f
’
(
x
i
)
(
x
−
x
i
)
f(x) = f(x_i) + f’(x_i)(x - x_i)
f(x)=f(xi)+f’(xi)(x−xi)
迭代公式:
x
i
+
1
=
x
i
−
f
(
x
i
)
/
f
′
(
x
i
)
x_i+1=xi - f(x_i) / f'(x_i)
xi+1=xi−f(xi)/f′(xi)
这个题目中,曲线方程就是 f ( r e s ) = r e s ∗ r e s − x f(res)=res*res-x f(res)=res∗res−x,近似求解 f ( r e s ) = 0 f(res)=0 f(res)=0的解。
代码
class Solution {
public:
int mySqrt(int x) {
long long int res=x;
while(res*res>x)
{
res=(res+x/res)/2;
}
return res;
}
};