The greatest common divisor (GCD) of two integers
Notation:
Finding factors:
- Factors of 29: 1, 29
- Factors of 8: 1, 2, 4, 8
- Common factors: 1
Goal: Compute
$\gcd(a, b)$ fast without factoring!
The "block sizes that work" don't change when we replace the bigger number by the leftover (remainder).
flowchart TD
A(["Start: a, b"]) --> B["Divide: a = bq + r"]
B --> C{r == 0?}
C -- No --> D["Replace: a ← b, b ← r"]
D --> B
C -- Yes --> E(["GCD = b"])
style A fill:#7c4dff,color:#fff
style E fill:#00897b,color:#fff
Repeat:
- Divide:
$a = bq + r$ - Replace:
$(a, b) \to (b, r)$ - Stop when
$r = 0$
Answer: The last non-zero remainder is the GCD.
Last non-zero remainder:
| Step | Equation | |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | ||
| 5 |
Idea: You only care about the remainder after dividing by something.
Let
if
In other words:
Is
Since 6 divides 12, yes:
Is
Yes:
Find the remainder when
Examples:
-
$17 \bmod 5 = 2$ (since$17 = 5 \times 3 + 2$ ) -
$100 \bmod 7 = 2$ (since$100 = 7 \times 14 + 2$ ) -
$-3 \bmod 5 = 2$ (since$-3 = 5 \times (-1) + 2$ )
Compute
Method 1: Direct
Method 2: Reduce first
Compute
Method 1: Direct
Method 2: Reduce first
To compute
Idea: Break down the exponent using binary representation.
(because
Binary:
| Power | Calculation | Result mod 11 |
|---|---|---|
The modular inverse of
(i.e.,
Find
We need:
Testing:
$7 \times 1 = 7 \not\equiv 1$ $7 \times 2 = 14 \equiv 3 \not\equiv 1$ $7 \times 3 = 21 \equiv 10 \not\equiv 1$ $7 \times 4 = 28 \equiv 6 \not\equiv 1$ $7 \times 5 = 35 \equiv 2 \not\equiv 1$ $7 \times 6 = 42 \equiv 9 \not\equiv 1$ $7 \times 7 = 49 \equiv 5 \not\equiv 1$ -
$7 \times 8 = 56 \equiv 1$ ✓
Finds integers
This is used to compute modular inverses efficiently.
- Keeps numbers bounded (prevents overflow)
- Makes operations reversible (with modular inverse)
-
Foundation of RSA (encryption/decryption uses mod
$n$ ) - Diffie-Hellman key exchange
- Digital signatures
- Euclidean algorithm computes GCD fast
- Modular arithmetic = clock arithmetic (wrap around)
-
Modular inverse exists only when
$\gcd(a, n) = 1$ - Fast exponentiation uses binary representation
- All modern crypto uses modular arithmetic