In number theory, 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,

For example,
because
and
.
Algorithm
One way of calculating
and
is to use Newton's method to find a solution for the equation
, giving the iterative formula

The sequence
converges quadratically to
as
. It can be proven that if
is chosen as the initial guess, one can stop as soon as

to ensure that
For computing
for very large integers n, one can use the quotient of Euclidean division for both of the division operations. This has the advantage of only using integers for each intermediate value, thus making the use of floating point representations of large numbers unnecessary. It is equivalent to using the iterative formula

By using the fact that

one can show that this will still converge to
, and thus (because the sequence is integer-valued) arrive at it exactly in a finite number of steps.
Domain of computation
Although
is irrational for many
, the sequence
contains only rational terms when
is rational. Thus, with this method it is unnecessary to exit the field of rational numbers in order to calculate
, a fact which has some theoretical advantages.
Stopping criterion
One can prove that
is the largest possible number for which the stopping criterion

ensures
in the algorithm above.
In implementations which use number formats that cannot represent all rational numbers exactly (for example, floating point), a stopping constant less than one half should be used to protect against roundoff errors.
See also
External links