Federal Information Processing Standard 186-4 appendix C.4 gives (without reference) an algorithm intended to test if a positive integer $C$ (which can be thousands bits) is a square:
- Set $n$, such that $2^n>C\ge2^{(n-1)}$.
- $m=\lceil n/2\rceil$.
- $i=0$.
- Select $X_0$, such that $2^m>X_0\ge2^{(m-1)}$.
- Repeat
5.1 $i=i+1$.
5.2 $X_i=((X_{i-1})^2+C)/(2X_{i-1})$.
Until $(X_i)^2<2^m+C$. - If $C=\lfloor X_i\rfloor^2$, then status =
PERFECT SQUARE
.
Else status =NOT A PERFECT SQUARE
. - Return status.
At step 5.2, can we compute $X_i$ by Euclidean division (that is rounding down to the nearest integer)? In the affirmative, how do we prove the algorithm terminates, and yields correct status, regardless of the choice made at step 4? Towards this, what invariant condition should we prove is maintained during step 5?
I observe that in step 6 it's used $\lfloor X_i\rfloor$ rather then just $X_i$, and that's strange if $X_i$ is intended to be an integer. Also, the notes after the statement of the algorithm, intended to prove it correct, seem written with real values in mind.
Remark: A practical implementation could suppress $i$ (thus steps 3 and 5.1), and use a single $X$ for all the $X_i$. It could use an arbitrary integer type or class for at least $C$ and $X$.