§ Modular inverse calculation
- Easy way to calculate a−1 mod p is to use ap−2. We know that ap−1≡1 from Lagrane's theorem, so ap−2⋅a≡1, or a−1≡ap−2. This can be done fairly quickly with repeated exponentiation.
- Another way to do this is to use extended eucliean division. Suppose a≡0 (mod p). Then we can find numbers α,β such that aα+pβ=gcd(a,p)=1. If we look at the whole equation (mod p), we find that aα≡1 (mod p), or α is the modular inverse of a.
pair<int, int> euc(int x, int y) {
if (x < y) { return euc(y, x); }
if (x % y == 0) { return {0, 1}; }
int a, b; std::tie(a, b) = euc(y, x%y);
return {b, a - b*(x/y)};
}