modular-inverse-coprime-property

Wed Apr 01 2026

Modular inverses exists ONLY for co-prime elements

There are two ways to compute modular inverses: Fermat's little theorem and the extended Euclidean algorithm. Fermat gives you a1ap11(modp)a^{-1} \equiv a^{p-1-1} \pmod{p} directly, which works but requires exponentiation. The extended Euclidean algorithm doesn't use this trick at all. It just adds additional bookkeeping to the standard GCD computation to find the inverse, and it's more efficient.

But why does the extended Euclidean algorithm actually work? And why does the inverse only exist when gcd(a,n)=1\gcd(a, n) = 1?

The Diophantine equation connection

The extended Euclidean algorithm works because there will always exist a solution for the Diophantine equation ax+ny=gcd(a,n)a \cdot x + n \cdot y = \gcd(a, n). If we take mod  n\bmod\;n on both sides, the nyn \cdot y term vanishes and we get:

axgcd(a,n)(modn)a \cdot x \equiv \gcd(a, n) \pmod{n}

When gcd(a,n)=1\gcd(a, n) = 1, this becomes ax1(modn)a \cdot x \equiv 1 \pmod{n}, which means xx is the inverse of aa in Zn\mathbb{Z}_n. So the inverse exists if and only if aa and nn are coprime.

The time complexity is O(log(min(a,n)))O(\log(\min(a, n))). Why not max\max?

Zn\mathbb{Z}_n^* as a group

Zn={aZngcd(a,n)=1}\mathbb{Z}_n^* = \{a \in \mathbb{Z}_n \mid \gcd(a, n) = 1\} is the set of elements in Zn\mathbb{Z}_n that are coprime to nn. It doesn't include 0. The size of this group is φ(n)\varphi(n), Euler's totient function.

To verify it's actually a group, check the four axioms:

  1. Closure under multiplication. Let x,yZnx, y \in \mathbb{Z}_n^*. Since both xx and yy are coprime with nn, their product is also coprime with nn (i.e., gcd(xy,n)=1\gcd(x \cdot y, n) = 1). Now xymodnxyknx \cdot y \bmod n \equiv x \cdot y - k \cdot n for some integer kk. We need gcd(xykn,  n)=1\gcd(x \cdot y - k \cdot n,\; n) = 1.
  2. Associativity. Trivial.
  3. Identity. The element 1.
  4. Inverses. Every element has an inverse because they are coprime with nn, so a solution to the Diophantine equation exists since their gcd\gcd with nn is 1.

Double-and-add is fast exponentiation in different notation

"Double and add" and fast exponentiation are basically the same algorithm. They just differ in notation.

Double-and-add computes nPn \cdot P: scalar multiplication is just repeated point addition. Compute P,2P,4P,,2iPP, 2P, 4P, \ldots, 2^i P by doubling, until 2in2^i \leq n. Add 2iP2^i P to the result whenever the ii-th bit is set in nn. This runs in O(logn)O(\log n).

Fast exponentiation computes XyX^y: scalar exponentiation is just repeated multiplication. Compute X,X2,X4,,X2iX, X^2, X^4, \ldots, X^{2^i} by squaring, until 2iy2^i \leq y. Multiply X2iX^{2^i} into the result whenever the ii-th bit is set in yy. This runs in O(logy)O(\log y).