is the value with . It exists iff .
The three methods
1. Fermat’s little theorem — prime
long long inv(long long a, long long m) { return powmod(a % m, m - 2, m); }. The default when the modulus is a prime like or .
2. Extended Euclid — any coprime
long long inv(long long a, long long m) {
long long x, y;
if (extgcd(a, m, x, y) != 1) return -1; // no inverse
return (x % m + m) % m;
}, works for composite , and is slightly faster than modpow. See Extended Euclidean.
3. Euler’s theorem — any coprime
Requires factoring to compute $\varphi(m)$, so use extended Euclid instead unless is already known.
Batch computation
All inverses modulo a prime —
vector<long long> inv(n + 1);
inv[1] = 1;
for (int i = 2; i <= n; i++)
inv[i] = (m - (m / i) * inv[m % i] % m) % m;Derivation: write with , . Then , so , hence .
Essential for precomputing inverse factorials in rather than .
Inverses of arbitrary values — one modpow
Compute prefix products , invert only , then walk backwards:
vector<long long> batchInverse(vector<long long>& a, long long m) {
int n = a.size();
vector<long long> pref(n + 1, 1), res(n);
for (int i = 0; i < n; i++) pref[i+1] = pref[i] * a[i] % m;
long long cur = powmod(pref[n], m - 2, m);
for (int i = n - 1; i >= 0; i--) { res[i] = cur * pref[i] % m; cur = cur * a[i] % m; }
return res;
}instead of — a genuinely useful trick when inverses appear inside a hot loop.
Inverse factorials
fact[0] = 1;
for (int i = 1; i <= N; i++) fact[i] = fact[i-1] * i % MOD;
invFact[N] = powmod(fact[N], MOD - 2, MOD);
for (int i = N; i > 0; i--) invFact[i-1] = invFact[i] * i % MOD; // one modpow totalThen in . See Combinatorics.
When the inverse does not exist
Then has no inverse. Common causes: dividing by a multiple of the modulus, or a prime modulus with a numerator that happens to be a multiple of it (which makes the “fraction” genuinely , not undefined).
Options when :
- If in “solve ”, divide the whole congruence by (including the modulus) — see Linear Congruence.
- Factor out the shared primes and track their exponents separately. This is how and similar are computed.
- Use CRT to split a composite modulus into prime powers.
Division under a modulus, safely
valid only when . There is no “integer division” in modular arithmetic — is a completely different quantity and cannot be computed this way.
See also: Modular Arithmetic · Extended Euclidean · Linear Congruence