Newton Raphson method
1 | class Solution { |
Remarks:
TC: $O(\log \log x)$, SC: $O(1)$.
Each iteration reduces the error quadratically, which means it has quadratic convergence and is very fast. (誤差が前回の誤差の二乗の速さで減少する)
How to derive the formula?
We are trying to calculate $\sqrt{S}$, so we are trying to find a $x$ such that $x^2 = S$.Which could be presented as $f(x) = x^2 - S$, to find the zero point.
General Newtown Raphson:
$$
x_{n+1} = x_n - \frac{f(x_n)}{f’(x_n)}
$$In this problem, $f(x) = x^2 - S$, $f’(x) = 2x$,
So we have the iteration formula:
$$
x_{n+1} = x_n - \frac{x_n^2 - S}{2x_n} = \frac{1}{2}\left(x_n + \frac{S}{x_n}\right)
$$Where $S$ is the parameter $x$ in the question.