Geometric & Algebraic Algorithms

the modular inverse

In ordinary arithmetic, dividing by 3 means multiplying by 1/3, the number that turns 3 back into 1. In clock-style modular arithmetic, where you only keep remainders mod m, there are no fractions — but you can still ask: which whole number, multiplied by a, gives a remainder of 1 mod m? That number is the modular inverse of a, written a^(-1) mod m, and it is how you divide inside modular arithmetic. For example, mod 7 the inverse of 3 is 5, because 3*5 = 15 leaves remainder 1.

Precisely, a^(-1) mod m is the integer x in the range 0..m-1 with a*x = 1 mod m. The crucial fact is when it exists: an inverse exists if and only if gcd(a, m) = 1, that is, a and m share no common factor. The reason is Bezout's identity — gcd(a, m) = 1 means there are integers x, y with a*x + m*y = 1, and reading that equation mod m kills the m*y term, leaving a*x = 1 mod m, so x is the inverse. This gives the standard way to compute it: run the extended Euclidean algorithm on (a, m), take its coefficient x, and reduce it into 0..m-1. When m is prime there is also Fermat's little theorem, which gives a^(-1) = a^(m-2) mod m, computable by fast modular exponentiation.

Modular inverses are everywhere in number-theoretic algorithms. They let you solve linear congruences a*x = b mod m (multiply both sides by a^(-1)), they make the Chinese remainder theorem's reconstruction formula work, and they are the heart of RSA, where the private decryption exponent is the inverse of the public exponent modulo a certain number. The single honest pitfall to remember: not every element has an inverse. Mod 12, the number 4 has no inverse because gcd(4, 12) = 4, not 1 — no multiple of 4 ever leaves remainder 1 mod 12. So you must check gcd is 1 before assuming you can divide.

Inverse of 3 mod 7: try x=5, 3*5=15=1 mod 7, so 3^(-1) = 5. Via Fermat (7 prime): 3^(7-2) = 3^5 = 243 = 5 mod 7, same answer. But mod 12, 4 has NO inverse: 4*1=4, 4*2=8, 4*3=0, ... never 1, because gcd(4,12)=4.

An inverse exists exactly when gcd(a, m) = 1; compute it by extended Euclid (or Fermat if m is prime).

No inverse exists unless gcd(a, m) = 1; the Fermat shortcut a^(m-2) only works when m is prime, so do not apply it to composite moduli.

Also called
multiplicative inverse mod mmodular reciprocal模逆元模乘法反元素