guest@itl:~/home/algebra$
templates/modular-inverse.cpp
compilable
$cat templates/modular-inverse

Modular Inverse

Modular multiplicative inverse via Fermat's little theorem, extended Euclidean, and linear precomputation.

[Algebra]|
Jul 9, 2026
|explanatory_notes.md|
#modular-inverse#fermat#extended-gcd#precomputation
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

ll extgcd(ll a, ll b, ll& x, ll& y) {
  if (!b) {
    x = 1;
    y = 0;
    return a;
  }
  ll x1, y1;
  ll g = extgcd(b, a % b, x1, y1);
  x = y1;
  y = x1 - (a / b) * y1;
  return g;
}

ll invFermat(ll a, ll mod) {
  ll res = 1, e = mod - 2;
  a %= mod;
  while (e > 0) {
    if (e & 1) {
      res = (__int128)res * a % mod;
    }
    a = (__int128)a * a % mod;
    e >>= 1;
  }
  return res;
}

ll invExtended(ll a, ll m) {
  ll x, y;
  ll g = extgcd(a, m, x, y);
  if (g != 1) {
    return -1;
  }
  return (x % m + m) % m;
}

vector<ll> invPrecompute(ll n, ll mod) {
  vector<ll> inv(n + 1);
  inv[1] = 1;
  for (ll i = 2; i <= n; i++)
    inv[i] = mod - (mod / i) % mod * inv[mod % i] % mod;
  return inv;
}
46 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Modular Inverse

Find xx such that ax1(modm)a \cdot x \equiv 1 \pmod{m}. A solution exists iff gcd(a,m)=1\gcd(a, m) = 1.

Methods

  • Fermat's Little Theorem (prime mm only) — compute am2modma^{m-2} \bmod m via binary exponentiation. O(logm)O(\log m) per query

  • Extended Euclidean (any mm) — solve ax+my=gcd(a,m)ax + my = \gcd(a, m) for xx, then normalize. O(logm)O(\log m) per query

  • Linear Precomputation (prime mm only) — builds inv[1..n] in O(n)O(n) using the recurrence:
  • inv[i]=mmiinv[mmodi]modm\text{inv}[i] = m - \left\lfloor \frac{m}{i} \right\rfloor \cdot \text{inv}[m \bmod i] \bmod m

    After that, each lookup is O(1)O(1).

    When to Use

  • Combinatorics mod prime — computing C(n,r)modpC(n, r) \bmod p requires modular inverses of factorials

  • Division under a modulus — replace a/bmodma / b \bmod m with ab1modma \cdot b^{-1} \bmod m

  • Batch queries — when you need inverses for 11 through nn, linear precomputation is optimal
  • Complexity

  • Fermat — O(1)O(1) precompute, O(logm)O(\log m) per query

  • Extended Euclidean — O(1)O(1) precompute, O(logm)O(\log m) per query

  • Linear precomputation — O(n)O(n) precompute, O(1)O(1) per query