1. Reduce base
Take the base modulo p up front to keep numbers small.
base = base % modTyporithm · medium
Step 1 of 8 · intro card
Math & Number Theory
For a prime modulus p, the inverse of a is a^(p-2) mod p by Fermat's little theorem, found with fast modular exponentiation.
A modular inverse of a is the value x with a*x ≡ 1 (mod p) — division in modular arithmetic.
Fermat's little theorem says a^(p-1) ≡ 1 (mod p) for prime p and a not divisible by p, so a^(p-2) ≡ a^(-1).
Computing a^(p-2) with square-and-multiply runs in O(log p); for a composite modulus use the extended Euclidean algorithm instead.
inverse = a^(p-2) mod p.
Needs a prime modulus p.
Use extended Euclid when p is not prime.
function modPow(base, exp, mod) {
let result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 === 1) {
result = (result * base) % mod;
}
exp = Math.floor(exp / 2);
base = (base * base) % mod;
}
return result;
}
function modInverse(a, p) {
return modPow(a, p - 2, p);
}Connect each part of the code to the concept before you type.
Take the base modulo p up front to keep numbers small.
base = base % modFold the base into the result on a set bit, reducing modulo p.
result = (result * base) % modSquare the base each step so the exponent is consumed in binary.
base = (base * base) % modBy Fermat's little theorem a^(p-1) ≡ 1, so a^(p-2) is the inverse of a mod p.
return modPow(a, p - 2, p)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputFind inverse of 3 modulo 11
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state