TExcelTAD
Home › Number Theory & Cryptography › Modular Inverses

Modular Inverses

"Dividing" modulo nn means multiplying by an inverse: the number a−1a^{-1} with a⋅a−1≡1(modn)a \cdot a^{-1} \equiv 1 \pmod{n}. RSA's private key is an inverse, every elliptic-curve addition computes one, and the Chinese remainder theorem is built from them. There are three ways to compute it.

Existence

aa has an inverse modulo nn if and only if gcd⁡(a,n)=1\gcd(a, n) = 1, and then the inverse is unique modulo nn. (If ab≡ab′≡1ab \equiv ab' \equiv 1, multiply ab≡ab′ab \equiv ab' by bb to get b≡b′b \equiv b'.)

Method 1: extended Euclid

From ax+ny=1ax + ny = 1 we read a−1≡xa^{-1} \equiv x. This works for any modulus and costs O(log⁡n)O(\log n) steps (The Extended Euclidean Algorithm). Python's pow(a, -1, n) does exactly this.

Method 2: Fermat (prime modulus)

If pp is prime and p∤ap \nmid a, then ap−1≡1a^{p-1} \equiv 1 (Fermat's Little Theorem), so a−1≡ap−2(modp)a^{-1} \equiv a^{p-2} \pmod{p}. One modular exponentiation, and it is easy to implement in constant time, which is why curve libraries often use it.

python · try it yourself
def egcd_inverse(a, n):
    r0, x0, r1, x1 = a % n, 1, n, 0
    while r1:
        q = r0 // r1
        r0, r1, x0, x1 = r1, r0 - q * r1, x1, x0 - q * x1
    if r0 != 1:
        raise ValueError("not invertible")
    return x0 % n

p = 2**127 - 1                    # a Mersenne prime
a = 123456789123456789
i1, i2, i3 = egcd_inverse(a, p), pow(a, p - 2, p), pow(a, -1, p)
print(i1 == i2 == i3, a * i1 % p)
print(egcd_inverse(7, 40), pow(7, -1, 40))
True 1
23 23

Method 3: batch inversion

Need the inverses of many numbers a1,…,aka_1, \ldots, a_k modulo pp? Montgomery's trick computes the prefix products, inverts only the last one, and walks back: 3(k−1)3(k - 1) multiplications and one inversion instead of kk inversions.

python · try it yourself
def batch_inverse(xs, p):
    prefix = [1]
    for x in xs:
        prefix.append(prefix[-1] * x % p)
    inv = pow(prefix[-1], -1, p)          # the only inversion
    out = [0] * len(xs)
    for i in range(len(xs) - 1, -1, -1):
        out[i] = inv * prefix[i] % p      # = 1 / xs[i]
        inv = inv * xs[i] % p             # = 1 / (x_0 ... x_{i-1})
    return out

p = 10**9 + 7
xs = [2, 3, 10, 999, 123456]
inv = batch_inverse(xs, p)
print(inv)
print([x * y % p for x, y in zip(xs, inv)])
[500000004, 333333336, 700000005, 874874881, 78351802]
[1, 1, 1, 1, 1]

A table of all inverses modulo pp

For a prime pp there is even a recurrence that fills in all inverses of 1,…,p−11, \ldots, p - 1 in linear time: i−1≡−⌊p/i⌋⋅(p mod i)−1i^{-1} \equiv -\lfloor p/i \rfloor \cdot (p \bmod i)^{-1}. It comes from p=⌊p/i⌋ i+(p mod i)≡0p = \lfloor p/i \rfloor\, i + (p \bmod i) \equiv 0.

python · try it yourself
p = 13
inv = [0, 1]
for i in range(2, p):
    inv.append(-(p // i) * inv[p % i] % p)
print(inv[1:])
print(all(i * inv[i] % p == 1 for i in range(1, p)))
[1, 7, 9, 10, 8, 11, 2, 5, 3, 4, 6, 12]
True

In software

  • RSA libraries compute d=e−1 mod λ(n)d = e^{-1} \bmod \lambda(n) and the CRT coefficient q−1 mod pq^{-1} \bmod p once at key generation.
  • Elliptic-curve code works in projective coordinates and does a single inversion (often by Fermat, ap−2a^{p-2}) at the end of a scalar multiplication. Batch inversion is used when many points are normalized together, for example in signature batch verification.

Exercises

Exercise 1: By hand

Find 7−1 mod 407^{-1} \bmod 40.

Answer
Solution

40=5⋅7+540 = 5 \cdot 7 + 5, 7=1⋅5+27 = 1 \cdot 5 + 2, 5=2⋅2+15 = 2 \cdot 2 + 1. Back-substitute: 1=5−2⋅2=5−2(7−5)=3⋅5−2⋅7=3(40−5⋅7)−2⋅7=3⋅40−17⋅71 = 5 - 2 \cdot 2 = 5 - 2(7 - 5) = 3 \cdot 5 - 2 \cdot 7 = 3(40 - 5 \cdot 7) - 2 \cdot 7 = 3 \cdot 40 - 17 \cdot 7. So 7−1≡−17≡237^{-1} \equiv -17 \equiv 23. Check: 7⋅23=161=4⋅40+17 \cdot 23 = 161 = 4 \cdot 40 + 1.

Exercise 2: Fermat inverse

Use ap−2a^{p-2} to find 3−1 mod 113^{-1} \bmod 11.

Answer
Solution

39 mod 113^9 \bmod 11: 32=93^2 = 9, 34=81≡43^4 = 81 \equiv 4, 38≡16≡53^8 \equiv 16 \equiv 5, 39≡15≡43^9 \equiv 15 \equiv 4. Check: 3⋅4=12≡13 \cdot 4 = 12 \equiv 1.

Exercise 3: Count the work (code)

Batch-invert the numbers 1,2,…,10001, 2, \ldots, 1000 modulo p=109+7p = 10^9 + 7 and confirm every product is 1. How many inversions did Montgomery's trick use?

Answer

One inversion; all 1000 products are 1.

Solution
python · try it yourself
p = 10**9 + 7
xs = list(range(1, 1001))
prefix = [1]
for x in xs:
    prefix.append(prefix[-1] * x % p)
inv_all, out = pow(prefix[-1], -1, p), [0] * len(xs)
for i in range(len(xs) - 1, -1, -1):
    out[i] = inv_all * prefix[i] % p
    inv_all = inv_all * xs[i] % p
print(all(x * y % p == 1 for x, y in zip(xs, out)), out[1], out[999])
True 500000004 857000006

out[1] is the inverse of 2, which is (p+1)/2=500000004(p + 1)/2 = 500000004.

Test yourself

For a prime pp and p∤ap \nmid a, the inverse of aa modulo pp is…

  1. apa^{p}
  2. ap−1a^{p-1}
  3. ap−2a^{p-2}
  4. p−ap - a

Montgomery's batch inversion of kk numbers needs how many modular inversions?

  1. kk
  2. log⁡k\log k
  3. 1
  4. k2k^2

Which has no inverse modulo 26?

  1. 3
  2. 5
  3. 13
  4. 25