modular-inverse-coprime-property
Modular inverses exists ONLY for co-prime elements
There are two ways to compute modular inverses: Fermat's little theorem and the extended Euclidean algorithm. Fermat gives you directly, which works but requires exponentiation. The extended Euclidean algorithm doesn't use this trick at all. It just adds additional bookkeeping to the standard GCD computation to find the inverse, and it's more efficient.
But why does the extended Euclidean algorithm actually work? And why does the inverse only exist when ?
The Diophantine equation connection
The extended Euclidean algorithm works because there will always exist a solution for the Diophantine equation . If we take on both sides, the term vanishes and we get:
When , this becomes , which means is the inverse of in . So the inverse exists if and only if and are coprime.
The time complexity is . Why not ?
as a group
is the set of elements in that are coprime to . It doesn't include 0. The size of this group is , Euler's totient function.
To verify it's actually a group, check the four axioms:
- Closure under multiplication. Let . Since both and are coprime with , their product is also coprime with (i.e., ). Now for some integer . We need .
- Associativity. Trivial.
- Identity. The element 1.
- Inverses. Every element has an inverse because they are coprime with , so a solution to the Diophantine equation exists since their with is 1.
Double-and-add is fast exponentiation in different notation
"Double and add" and fast exponentiation are basically the same algorithm. They just differ in notation.
Double-and-add computes : scalar multiplication is just repeated point addition. Compute by doubling, until . Add to the result whenever the -th bit is set in . This runs in .
Fast exponentiation computes : scalar exponentiation is just repeated multiplication. Compute by squaring, until . Multiply into the result whenever the -th bit is set in . This runs in .