What is Modular Multiplicative Inverse? #
If , is called a inverse of a(modulo p), referred to as . We usually use the minimum positive inverse.
The use of Inverse #
The inverse is used when calculating the modulo of division.
The ways to calculate the inverse of a number #
The Extended Euclidean algorithm #
We can rewrite as which can be solved using the Extended Euclidean algorithm.
void exgcd(int a, int b, int& x, int& y) {
if (b == 0) {
x = 1, y = 0;
return;
}
exgcd(b, a % b, y, x);
y -= a / b * x;
}
The Fermat’s Little Theorem #
According to Fermat’s Little Theorem , thus , . We can calculate it using Exponentiation by squaring.
inline int qpow(long long a, int b) {
int ans = 1;
a = (a % p + p) % p;
for (; b; b >>= 1) {
if (b & 1) ans = (a * ans) % p;
a = (a * a) % p;
}
return ans;
}
Calculate consecutive inverses in linear time #
inv[1] = 1;
for (int i = 2; i <= n; ++i) inv[i] = (long long)(p - p / i) * inv[p % i] % p;
Modulo of Combinations #
Calculate
When n and m are not too big #
We can use the inverse to calculate
Calculate the inverse of factorial #
Thereforeis an inverse of .
fact[0] = 1;
for (int i = 1; i < maxn; i++) {
fact[i] = fact[i - 1] * i %mod;
}
inv[maxn - 1] = power(fact[maxn - 1], mod - 2);
for (int i = maxn - 2; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1) %mod;
}
When n and m are really big but p is not too big #
long long Lucas(long long n, long long m, long long p) {
if (m == 0) return 1;
return (C(n % p, m % p, p) * Lucas(n / p, m / p, p)) % p;
}