69. Square root of x
topic description
Given a non-negative integer x, compute and return the arithmetic square root of x.
Since the return type is an integer, only the integer part of the result is kept, and the decimal part will be discarded.
Note: Any built-in exponential functions and operators are not allowed, such as pow(x, 0.5) or x ** 0.5
input Output
输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
answer
Newton iteration method
Equivalent to solving f ( x ) = x 2 − af(x) = x^2 - af(x)=x2−positive root of a
use xn x_nxnThe tangent to intercept the x-axis, get the abscissa xn + 1 x_{n+1}xn+1, continue with xn + 1 x_{n+1}xn+1To cut the x-axis, it will gradually converge to the root of the function
the code
class Solution {
public:
int mySqrt(int x) {
long res = x;
while (res * res > x)
res = (res + x / res) / 2;
return (int) res;
}
};