An Easy Way to Find Modular Inverses

Revision en1, by Forestmy17, 2026-04-28 22:31:56

Maybe you are still using Fermat's Little Theorem to find inverses modulo a prime number $$$p$$$.

If p is prime and x is not divisible by p, then by Fermat's Little Theorem:

$$$x^{p-1}\equiv 1\pmod p$$$

Therefore,

$$$x^{p-2}\equiv x^{-1}\pmod p$$$

So the usual way to find the modular inverse is to use binary exponentiation:

int binpow(int a, int n) {
    int res = 1;
    while (n) {
        if (n&1) res = 1LL * res * a % mod;
        a = 1LL * a * a % mod;
        n >>= 1;
    }
    return res;
}
int inv(int x) {
    return binpow(x, mod - 2);
}

This works perfectly fine. But for such a common operation, it is nice to have something shorter.

For example, we can write the modular inverse like this:

int inv(int x) {
    return x == 1 ? 1 : mod - 1LL * (mod / x) * inv(mod % x) % mod;
}

Now let's prove why this formula works.

First, write mod using division with remainder:

$$$mod = (mod / x) * x + mod \% x$$$

Therefore,

$$$mod \% x = mod - (mod / x) * x$$$

Since we are working modulo mod, the value mod is congruent to 0, so:

$$$mod \% x\equiv -(mod/x) * x \pmod{mod}$$$

Now multiply both sides by $$$inv(mod\%x)$$$ $$$\big($$$ We know that $$$(mod \% x) * inv(mod \% x) \equiv 1 \pmod{mod}\big)$$$:

$$$1\equiv -(mod / x) * x * inv(mod \% x) \pmod{mod}$$$

Since mod is prime and x is not divisible by mod, division by x is valid modulo mod.

Dividing both sides by x, we get:

$$$x^{-1} \equiv -(mod / x) * inv(mod \% x) \pmod{mod}$$$

But $$$x^{-1}$$$ is exactly the modular inverse of x, so this gives us:

$$$inv(x) \equiv -(mod / x) * inv(mod \% x) \pmod{mod}$$$

Of course we want a non-negative value, so instead of returning the negative number directly, we add mod:

$$$inv(x) \equiv mod - (mod / x) * inv(mod \% x) \pmod{mod}$$$

So we have derived the recursive formula:

int inv(int x) {
    return x == 1 ? 1 : mod - 1LL * (mod / x) * inv(mod % x) % mod;
}

The recursion stops at x = 1 because inv(1) = 1.

The complexity is $$$O(\log mod)$$$, similar to the first solution, but the implementation is much shorter than binary exponentiation.

Tags modular inverse, math, number theory, modular arithmetic

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
ru2 Russian Forestmy17 2026-04-28 22:40:00 2 Мелкая правка: '%x)$ $\big($мы знаем, ' -> '%x)$ $\big ($ мы знаем, '
ru1 Russian Forestmy17 2026-04-28 22:38:24 2349 Первая редакция перевода на Русский
en1 English Forestmy17 2026-04-28 22:31:56 2269 Initial revision (published)