Sub topic 11
Computing Modular Inverses
This chapter assumes you have read the chapter on the extended Euclidean algorithm and know what extended_gcd(a, b) returns: a triple (g, x, y) with a*x + b*y == g. It also assumes you are comfortable with the % operator and with congruence notation, where a ≡ b (mod m) means that m divides a - b.
In ordinary arithmetic you undo multiplication by dividing. In modular arithmetic there is no division operator. The tool that takes its place is the modular inverse. Computing it is the most common practical use of the extended Euclidean algorithm.
What a Modular Inverse Is
Let m be a positive integer. A modular inverse of a modulo m is an integer x such that
a * x ≡ 1 (mod m)
For example, 4 is an inverse of 3 modulo 11, because 3 * 4 = 12 = 11 + 1. Multiplying by 4 modulo 11 undoes multiplying by 3: if y ≡ 3 * k (mod 11), then 4 * y ≡ 12 * k ≡ k (mod 11).
Inverses are only defined up to congruence. If x is an inverse, so is x + 11, x - 22, and so on. When people say "the" inverse, they mean the representative in the range 0 to m - 1.
Some numbers have no inverse at all. Try to find an inverse of 6 modulo 15. The multiples of 6 modulo 15 are 6, 12, 3, 9, 0, 6, 12, ... and the cycle never reaches 1. The next section explains why.
When an Inverse Exists
Theorem. The integer a has an inverse modulo m if and only if gcd(a, m) = 1.
Proof, "if" direction. Suppose gcd(a, m) = 1. By Bézout's identity there are integers x and y with a*x + m*y = 1. Then a*x - 1 = -m*y is a multiple of m, so a*x ≡ 1 (mod m). The Bézout coefficient x is an inverse.
Proof, "only if" direction. Suppose a*x ≡ 1 (mod m). Then a*x - 1 = k*m for some integer k, so 1 = a*x - k*m. Any common divisor of a and m divides the right-hand side, so it divides 1. Therefore gcd(a, m) = 1.
The proof also gives you the algorithm. Run the extended Euclidean algorithm on a and m. If the gcd is 1, the coefficient of a is an inverse. If the gcd is not 1, no inverse exists.
Uniqueness. If x and x' are both inverses of a, then a*(x - x') ≡ 0 (mod m). Multiply both sides by x: (x*a)*(x - x') ≡ x - x' ≡ 0 (mod m). So any two inverses are congruent, and exactly one lies in 0..m-1.
For 6 modulo 15, gcd(6, 15) = 3. Every multiple of 6, reduced modulo 15, is still a multiple of 3, so it can never equal 1.
The Implementation
def extended_gcd(a, b):
# Returns (g, x, y) with a*x + b*y == g == gcd(a, b), for a, b >= 0
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
old_t, t = t, old_t - q * t
return old_r, old_s, old_t
def mod_inverse(a, m):
if m <= 0:
raise ValueError("modulus must be positive")
g, x, _ = extended_gcd(a % m, m)
if g != 1:
raise ValueError("inverse does not exist")
return x % m
print(mod_inverse(3, 11)) # 4
print(mod_inverse(17, 43)) # 38
print(mod_inverse(-3, 11)) # 7, since -3 * 7 = -21 = 1 (mod 11)
print(pow(3, -1, 11)) # 4, built-in since Python 3.8Two details in mod_inverse matter.
a % mfirst. This step reduces large inputs and turns negative inputs into the range0..m-1, whichextended_gcdexpects. Becausea % m ≡ a (mod m), the inverse is unchanged.x % mlast. The Bézout coefficient is often negative. In Python,%with a positive modulus always returns a non-negative result, sox % mgives the canonical representative.
A Full Trace: the Inverse of 17 Modulo 43
The call mod_inverse(17, 43) runs extended_gcd(17, 43). The table shows the state after each loop iteration. Only r (the remainder) and s (the coefficient of 17) matter for the inverse.
| Iteration | q | old_r | r | old_s | s |
|---|---|---|---|---|---|
| start | – | 17 | 43 | 1 | 0 |
| 1 | 0 | 43 | 17 | 0 | 1 |
| 2 | 2 | 17 | 9 | 1 | -2 |
| 3 | 1 | 9 | 8 | -2 | 3 |
| 4 | 1 | 8 | 1 | 3 | -5 |
| 5 | 8 | 1 | 0 | -5 | 43 |
The first iteration has q = 0 and only swaps the pair, because 17 < 43. The loop stops with old_r = 1 and old_s = -5. Check the result: 17 * (-5) = -85 = -2 * 43 + 1, so -5 is an inverse. Normalizing gives -5 % 43 = 38, and 17 * 38 = 646 = 15 * 43 + 1.
The final value s = 43 is no coincidence. When the loop ends, s is always ±m / g, which here is ±43. This gives a quick sanity check when you trace by hand.
A Leaner Version
The t coefficient (the coefficient of m) is never used, so you can drop it. This version also runs Euclid's algorithm in the natural order, with m first, so it skips the initial swap iteration.
def mod_inverse_lean(a, m):
if m <= 0:
raise ValueError("modulus must be positive")
r0, r1 = m, a % m
s0, s1 = 0, 1 # coefficients of a for r0 and r1
while r1 != 0:
q = r0 // r1
r0, r1 = r1, r0 - q * r1
s0, s1 = s1, s0 - q * s1
if r0 != 1:
raise ValueError("inverse does not exist")
return s0 % m
print(mod_inverse_lean(17, 43)) # 38
print(mod_inverse_lean(7, 26)) # 15
print(mod_inverse_lean(5, 1)) # 0The invariant is r0 ≡ s0 * a (mod m) and r1 ≡ s1 * a (mod m). It holds at the start (m ≡ 0 * a and a ≡ 1 * a) and is preserved because both updates apply the same linear combination. When r0 = 1, s0 * a ≡ 1.
Edge Cases
| Input | Behavior | Reason |
|---|---|---|
| `m <= 0` | Error | Congruence modulo 0 or a negative number is not what callers mean. Reject it explicitly. |
| `m == 1` | Returns 0 | Every integer is congruent to 0 modulo 1, and `0 ≡ 1 (mod 1)`. `pow(5, -1, 1)` also returns 0. |
| `a == 0`, `m > 1` | Error | `gcd(0, m) = m ≠ 1`. |
| `a < 0` | Works | `a % m` maps it into range first. |
| `a >= m` | Works | Same reduction. The inverse of 45 modulo 43 equals the inverse of 2. |
| `gcd(a, m) > 1` | Error | No inverse exists, as the theorem shows. |
Alternatives: Fermat and Euler
If m is prime and a is not a multiple of m, Fermat's little theorem says a^(m-1) ≡ 1 (mod m), so a^(m-2) is an inverse. More generally, Euler's theorem gives a^(φ(m)-1) when gcd(a, m) = 1, where φ is Euler's totient function.
p = 43
print(pow(17, p - 2, p)) # 38, same as the extended Euclidean result| Method | Requires | Cost | Notes |
|---|---|---|---|
| Extended Euclid | Nothing beyond `gcd(a, m) = 1` | O(log m) division steps | Reports non-existence for free. Works for any modulus. |
| Fermat, `a^(m-2)` | `m` prime | O(log m) multiplications modulo `m` | Simple with a fast `pow`. Gives a wrong answer silently if `m` is not prime. |
| Euler, `a^(φ(m)-1)` | Knowing `φ(m)` | Factoring `m`, then exponentiation | Rarely practical, since computing `φ(m)` is as hard as factoring. |
| `pow(a, -1, m)` | Python 3.8+ | Extended Euclid internally | Raises `ValueError` if no inverse exists. Use this in production Python. |
Fermat inversion is popular in competitive programming and in constant-time cryptographic code, where the fixed sequence of operations avoids data-dependent branches. For general use, the extended Euclidean algorithm is the default.
Using Inverses: Linear Congruences
To solve a*x ≡ b (mod m) when gcd(a, m) = 1, multiply both sides by the inverse: x ≡ b * a⁻¹ (mod m).
When g = gcd(a, m) > 1, the congruence has a solution only if g divides b. In that case divide everything by g, solve the reduced congruence modulo m/g, and you get exactly g solutions modulo m.
def extended_gcd(a, b):
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
old_t, t = t, old_t - q * t
return old_r, old_s, old_t
def solve_linear_congruence(a, b, m):
# All x in 0..m-1 with a*x = b (mod m)
g, x, _ = extended_gcd(a % m, m)
if b % g != 0:
return []
step = m // g
x0 = (x * (b // g)) % step
return [x0 + k * step for k in range(g)]
print(solve_linear_congruence(17, 5, 43)) # [36]
print(solve_linear_congruence(6, 9, 15)) # [4, 9, 14]
print(solve_linear_congruence(6, 10, 15)) # []Here x satisfies a*x ≡ g (mod m). Dividing through by g shows that x is the inverse of a/g modulo m/g, which is why x * (b // g) solves the reduced congruence.
Using Inverses: the RSA Private Key
RSA key generation computes the private exponent d as the inverse of the public exponent e modulo φ(n). Here is the classic toy example with primes 61 and 53:
p, q = 61, 53
n = p * q # 3233
phi = (p - 1) * (q - 1) # 3120
e = 17 # gcd(17, 3120) = 1
d = pow(e, -1, phi) # 2753, since 17 * 2753 = 46801 = 15 * 3120 + 1
message = 65
cipher = pow(message, e, n)
print(d, cipher, pow(cipher, d, n)) # 2753 2790 65Key generation must choose an e that is coprime to φ(n). Otherwise the inverse does not exist and pow raises ValueError. The modulus here is not prime, so Fermat inversion cannot be used, and the extended Euclidean algorithm is required.
Exercises
Exercise
Compute the inverse of 7 modulo 26 by hand using the extended Euclidean algorithm, and check your answer.
Show answer
26 = 37 + 5, 7 = 15 + 2, 5 = 22 + 1. Back-substituting: 1 = 5 - 22 = 5 - 2(7 - 5) = 35 - 27 = 3(26 - 37) - 27 = 326 - 117. The coefficient of 7 is -11, and -11 mod 26 = 15. Check: 7 15 = 105 = 426 + 1.
Exercise
Does 6 have an inverse modulo 15? Find all solutions of 6x ≡ 9 (mod 15) in the range 0..14.
Show answer
No inverse exists, because gcd(6, 15) = 3. The congruence still has solutions, because 3 divides 9. Dividing by 3 gives 2x ≡ 3 (mod 5). The inverse of 2 modulo 5 is 3, so x ≡ 9 ≡ 4 (mod 5). The solutions modulo 15 are 4, 9, and 14. Check: 6*4 = 24 ≡ 9 (mod 15).
Exercise
A colleague writes return x instead of return x % m at the end of mod_inverse. Is the result still a valid inverse, and what problems can this cause?
Show answer
Yes, the result is still congruent to the canonical inverse, so a*x ≡ 1 (mod m) holds. But the result may be negative (for example -5 instead of 38 for a = 17, m = 43). This breaks callers that use the result as an array index, compare it with other residues, or expect it in 0..m-1. In languages whose % can return negative values, later arithmetic can also give inconsistent results.
Exercise
Why is pow(a, m - 2, m) unsafe as a general-purpose inverse function, even when gcd(a, m) = 1?
Show answer
Fermat's little theorem only holds for prime m. For composite m the result is usually wrong, and nothing signals the error. For example, with a = 5 and m = 12, pow(5, 10, 12) = 1, but the true inverse is 5, because 5*5 = 25 ≡ 1 (mod 12). The extended Euclidean algorithm works for any modulus and reports when no inverse exists.