Proofs: Batch modular inverse
These are the human proofs of Batch modular inverse, at full length.
Batch modular inverse returns every inverse, or a divisor of m when one does not exist full
This proof shows: correctness.
Claim. Let and let be residues modulo , with . If every is a unit modulo , the algorithm returns with for each , and it uses modular multiplications and one inversion for . If some is not a unit, line L6 stops with , a divisor of .
The empty case. For , line L1 returns the empty list, which is correct.
Forward pass. Lines L2 to L4 set and . By induction on , for . This uses multiplications.
When the product is invertible. A product of units is a unit, and conversely, if is a unit with inverse , then for each
so is a unit. Hence if and only if every is a unit modulo . Line L5 computes and, when , by the extended Euclidean algorithm. If some is not a unit, then and , and line L6 stops as claimed. From now on, every is a unit.
Backward pass. We show that at the start of the iteration of line L7 with index , for , the invariant holds.
- Start. For , it holds by line L5.
- Step. Assume at the start of the iteration for . Line L8 sets
which is the correct output for position . Line L8 reads , which has not been overwritten yet, because the loop writes only positions before it reaches index . Line L9 sets , which is the invariant for .
After the last iteration, , the invariant gives , and line L10 sets . If , the loop does not run and directly by line L5. So every is the inverse of . The backward pass makes two multiplications per iteration, in total.
Count. The two passes use modular multiplications, and line L5 is the only inversion.