Integer square root
In number theory (a branch of mathematics), the integer square root (isqrt) of a positive integer n is the positive integer m which is the greatest integer less than or equal to the square root of n,
- <math>\mbox{isqrt}( n ) = \lfloor \sqrt n \rfloor.<math>
Table of contents |
Algorithm
To calculate √n, and in particular, isqrt(n), one can use Newton's method for the equation x2 – n = 0, which gives us the recursive formula
- <math>{x}_{k+1} = \frac{1}{2}\left(x_k + \frac{ n }{x}_{k}\right), \ k \ge 0.<math>
One can choose for example x0 = n as initial guess.
The sequence {x k} converges quadratically to √n as k→∞. It can be proved (the proof is not trivial) that one can stop as soon as
- | xk + 1 − xk | < 1
to ensure that <math>\lfloor x_{k+1} \rfloor=\lfloor \sqrt n \rfloor.<math>
Domain of computation
Let us note that even if √n is irrational for most n, the sequence {x k} contains only rational terms. Thus, with Newton's method one never needs to exit the field of rational numbers in order to calculate isqrt(n), a fact which has some theoretical advantages in number theory.
Stopping criterion
One can prove that <math>c=1<math> is the largest possible number for which the stopping criterion
- | xk+1 − xk | < c
ensures <math>\lfloor x_{k+1} \rfloor=\lfloor \sqrt n \rfloor<math> in the algorithm above.
Since actual computer calculations involve roundoff errors, one needs to use c < 1 in the stopping criterion, e.g.,
- | xk+1 − xk | < 0.5.
See also
- Wikisource: integer square root
Categories: Number theory | Algorithms