Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
解法一:牛顿迭代法
求n的平方根,即求f(x)=x2-n的零点
设初始值为x0,注,不要设为0,以免出现除数为0,见后。
则过(x0,f(x0))点的切线为g(x)=f(x0)+f‘(x0)*(x-x0)
g(x)与x轴的交点为x1=x0-f(x0)/f‘(x0)
递推关系为xn+1=xn-f(xn)/f‘(xn)
当收敛时即为解。
class Solution { public: int sqrt(int x) { double x0 = 1; double xn = (x0+x/x0)/2; while(abs(x0-xn) > 1e-5) { x0 = xn; xn = (x0+x/x0)/2; } return x0; } };
解法二:二分法
注意返回为int,结果会取整。
class Solution { public: int sqrt(int x) { long long low = 0; long long high = x; long long mid; while(low <= high) { mid = (low+high)/2; long long result = mid*mid; if(result == x) return mid; else if(result > x) high = mid-1; else low = mid+1; } return high; } };
时间: 2024-10-09 16:22:23