Proofs: Tonelli-Shanks algorithm
These are the human proofs of Tonelli-Shanks algorithm, at full length.
Correctness of the Tonelli-Shanks algorithm full
This proof shows: correctness, termination.
Let be an odd prime and an integer. All arithmetic is in the field . We use two facts about :
- (F1) The only solutions of are , since forces or by Euclid's lemma.
- (F2) If and for some , then the multiplicative order of is for some , because the order divides . If the order is with , then : it is not 1 by minimality, and its square is 1, so it is by (F1).
We also use Euler's criterion: for , if is a quadratic residue and otherwise.
Lines L1 and L2. If , then is the only root, and line L1 returns it. Otherwise, by Euler's criterion, line L2 returns NONE exactly when is a nonresidue, which is correct, since then no root exists. From here on is a nonzero quadratic residue, so .
Line L4. If , then with odd, so and is an integer. For , . So the returned value is a root.
Line L5. From here on . Exactly half of are nonresidues, so a nonresidue exists in (1 is a residue), and the search stops at the least one, , with .
Invariant. We claim that at the start of every pass of the loop of line L7 (that is, each time the test of line L7 is evaluated):
- (I1) ;
- (I2) ;
- (I3) ;
- (I4) .
Initialization. After line L6, , , and . (I1): . (I2): . (I3): . (I4): .
Maintenance. Suppose (I1) to (I4) hold and . By (I3) and (F2), has order for some with , and because . Line L8 squares until it reaches 1, so it finds exactly this , the least with , after squarings. By (F2), .
Since , the exponent , so line L9 is well defined and gives . Then by (I2).
Line L10 sets , , and . Check the invariant for the new values:
- (I1): .
- (I2): .
- (I3): .
- (I4): .
Termination. Each pass replaces by , so strictly decreases, and by (I4) it stays at least 1. So there are at most passes. Each inner loop also terminates: line L8 stops after squarings, and line L9 runs times. The search of line L5 stops, as shown above.
Conclusion. When the loop stops, , and (I1) gives . So line L11 returns a square root of modulo .
Together with the cases of lines L1, L2 and L4, this shows that the algorithm always terminates, returns NONE exactly when is a nonresidue, and otherwise returns an with .