Modular Inverse & Extended Euclidean Algorithm
For integers and :
- The modular inverse of modulo is an integer such that:
-
This means when you multiply by , divide by , the remainder is 1.
-
Not all numbers have inverses. has an inverse modulo only if (they are coprime).
Example
Find the inverse of :
We need .
Try values of :
- ✅
So the inverse is:
Extended Euclidean algorithm
The Euclidean Algorithm finds the greatest common divisor (gcd) of two integers and :
It repeatedly divides and takes remainders until the remainder is 0.
The Extended Euclidean Algorithm goes further: it finds integers such that:
These integers and are called Bezout coefficients.
👉 When , the coefficient is the modular inverse of .
2. Algorithm (Step-by-Step)
Given and :
-
Perform Euclidean Algorithm (repeated division):
Keep track of quotients and remainders.
-
Work backwards (substitution) to express gcd as a combination of and .
-
The coefficient in front of is its modular inverse (mod ), if gcd = 1.
3. Example: Find inverse of
We want such that:
That means solve:
Step 1: Euclidean Algorithm
So .
Step 2: Work backwards
From first step:
So:
Here:
Step 3: Modular inverse
So:
is the coefficient of . Modulo 7:
✅ Therefore, the inverse is:
4. General Algorithm (Compact Form)
function extended_gcd(a, b):
if b == 0:
return (a, 1, 0) # gcd, x, y
gcd, x1, y1 = extended_gcd(b, a mod b)
x = y1
y = x1 - (a // b) * y1
return (gcd, x, y)
If gcd = 1, then x
is the modular inverse of a mod b
.
Do you want me to also draw a tree-style diagram that shows how the substitutions work step by step (kind of like a flowchart), so it’s easier to see the backward substitution?