templates/modular-inverse.cpp
compilable
$cat templates/modular-inverse
Modular Inverse
Modular multiplicative inverse via Fermat's little theorem, extended Euclidean, and linear precomputation.
#modular-inverse#fermat#extended-gcd#precomputation
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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;
}38 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Modular Inverse
Find such that . A solution exists iff .
Methods
inv[1..n] in using the recurrence:After that, each lookup is .