Skip to main content
Math Foundations: Modular Arithmetic, GCD & Congruences
Lesson 2 of 3

Math Foundations: Modular Arithmetic, GCD & Congruences

Compute modular remainders, greatest common divisors, modular inverses, Euler's totient, and Chinese Remainder Theorem solutions in Python 3 for cryptography.

Beginner 26 min Cryptography

Learning objectives

  • Compute modular remainders and congruences including negative integers using Python's floor division rule
  • Apply the Euclidean and Extended Euclidean algorithms to test coprimality and find modular inverses
  • Calculate Euler's totient phi(n) and apply Fermat's Little Theorem and Euler's Theorem safely
  • Solve systems of pairwise-coprime congruences with the Chinese Remainder Theorem in Python 3

Recommended first: Introduction to Cryptography & Kerckhoffs's Principle

#Why this matters

Public-key systems such as RSA, Diffie-Hellman, and ECC operate over finite sets of integers rather than unbounded numbers. Modular arithmetic keeps values inside a fixed range while creating one-way traps: raising a number to a large power modulo n is fast, whereas reversing it without the secret key is infeasible.

In CTF challenges and security audits, you routinely compute modular inverses, check coprimality, and combine congruences. Mastering these five tools in Python 3 gives you the exact foundation needed for classical ciphers and RSA.

#The modulo operator and congruences

On a 12-hour clock, 17 hours past 12 wraps back to 5, so 17 mod 12 = 5. Formally, for any integer a and modulus n > 0:

a mod n = a - n * floor(a / n)

This floor rule explains negative numbers in Python: for -7 % 3, floor(-7 / 3) = -3, so -7 - 3 * (-3) = 2. Whenever n > 0, Python returns a non-negative remainder in 0..(n - 1).

We write a = b (mod n) (congruence) when n divides (a - b). Addition and multiplication reduce cleanly modulo n:

  • (a + b) mod n = ((a mod n) + (b mod n)) mod n
  • (a * b) mod n = ((a mod n) * (b mod n)) mod n
  • For large powers (a^k) mod n, call pow(a, k, n), which runs in O(log k) time; e.g. pow(2, 1000, 997) returns 16.

#GCD, Extended GCD, and modular inverses

GCD(a, b) is the largest integer dividing both a and b. Two integers are coprime when GCD(a, b) = 1. The Euclidean algorithm uses GCD(a, 0) = a and GCD(a, b) = GCD(b, a mod b):

  1. StartGCD(48, 18) -> 48 mod 18 = 12
  2. Step 2GCD(18, 12) -> 18 mod 12 = 6
  3. Step 3GCD(12, 6) -> 12 mod 6 = 0
  4. ResultGCD(6, 0) = 6

Instead of division, modular arithmetic multiplies by a modular inverse: an integer x with a * x = 1 (mod n). An inverse exists if and only if GCD(a, n) = 1.

The Extended Euclidean Algorithm finds x, y for Bezout's identity a * x + b * y = GCD(a, b). For 30 and 11, (-4) * 30 + 11 * 11 = -120 + 121 = 1, so 11^(-1) mod 30 = 11 and 30^(-1) mod 11 = -4 mod 11 = 7.

python
import math

def extended_gcd(a, b):
    if b == 0:
        return a, 1, 0
    g, x, y = extended_gcd(b, a % b)
    return g, y, x - (a // b) * y

def mod_inverse(a, n):
    g, x, _ = extended_gcd(a % n, n)
    if g != 1:
        raise ValueError("No inverse!")
    return x % n

print(math.gcd(48, 18))   # 6
print(mod_inverse(3, 11)) # 4
print(pow(7, -1, 26))     # 15 (Python 3.8+ built-in)

Calling mod_inverse(6, 15) raises ValueError because GCD(6, 15) = 3 != 1. Python 3.8+ provides pow(a, -1, n) natively.

#Euler's totient, Fermat's Little Theorem, and Euler's Theorem

Euler's totient phi(n) counts integers in 1..(n - 1) (for n > 1) coprime to n:

Case Formula Example
Prime p phi(p) = p - 1 phi(7) = 6
Distinct primes p, q phi(p * q) = (p - 1) * (q - 1) phi(15) = 2 * 4 = 8
Prime power p^k phi(p^k) = p^k - p^(k - 1) phi(8) = 8 - 4 = 4
Composite n = 12 Product over prime powers phi(12) = 4 (1, 5, 7, 11)
  • Fermat's Little Theorem: For prime p not dividing a, a^(p - 1) = 1 (mod p), giving a^(-1) = a^(p - 2) (mod p). For a = 2, p = 5, 2^3 mod 5 = 3.
  • Euler's Theorem: When GCD(a, n) = 1, a^phi(n) = 1 (mod n). RSA chooses e * d = 1 (mod phi(n)) so (m^e)^d = m (mod n).
Choosing a Modular Inverse Method
Fermat Shortcut: pow(a, p - 2, p)
  • Valid ONLY when modulus p is prime
  • Fails silently on composite moduli (n = 12)
  • Requires primality check first
Extended GCD / pow(a, -1, n)
  • Valid for ANY n when GCD(a, n) = 1
  • Raises ValueError when no inverse exists
  • Recommended default in Python 3.8+

#Chinese Remainder Theorem (CRT)

Given remainders of x modulo pairwise-coprime moduli n_1, ..., n_k (GCD(n_i, n_j) = 1 for i != j), CRT guarantees a unique solution modulo N = n_1 * ... * n_k by summing a_i * N_i * (N_i^(-1) mod n_i) (mod N) where N_i = N / n_i.

python
from functools import reduce

def phi(n):
    res, p, temp = n, 2, n
    while p * p < temp + 1:
        if temp % p == 0:
            while temp % p == 0:
                temp //= p
            res -= res // p
        p += 1
    return res - res // temp if temp > 1 else res

def crt(rems, mods):
    N = reduce(lambda a, b: a * b, mods)
    return sum(ai * (N // ni) * pow(N // ni, -1, ni) for ai, ni in zip(rems, mods)) % N

print(phi(12), phi(100))             # 4 40
print(pow(2, 10**18, 10**9 + 7))     # 719476260
print(crt([2, 3, 2], [3, 5, 7]))     # 23

CRT accelerates RSA decryption roughly 4x and powers Hastad's broadcast attack: encrypting the same unpadded message m with e = 3 under three pairwise-coprime RSA moduli lets CRT recover m^3 (m^3 < n_1 * n_2 * n_3), whose cube root reveals m.

#Defending / Common mistakes

  • Using Fermat's shortcut on composite moduli: pow(a, n - 2, n) works only for prime n; default to pow(a, -1, n).
  • Reducing exponents modulo n: 2^1000 mod 15 is not 2^(1000 mod 15) mod 15; call pow(2, 1000, 15) directly.
  • Skipping pairwise coprimality in CRT: Always check math.gcd(n_i, n_j) == 1 before inverting N_i.
  • Applying (p - 1)(q - 1) when p == q: Distinct primes are required; phi(p^2) = p^2 - p.

#Summary

  • Modular arithmetic wraps integers into 0..(n - 1) via a - n * floor(a / n), and pow(a, k, n) runs in O(log k).
  • A modular inverse exists if and only if GCD(a, n) = 1, computed via Extended GCD or pow(a, -1, n).
  • Euler's totient phi(n) generalizes Fermat's Little Theorem to Euler's Theorem (a^phi(n) = 1 mod n).
  • CRT solves pairwise-coprime congruences uniquely modulo N, enabling fast RSA decryption and Hastad's attack.

Lecture presentations

Slides on this topic: view them in the browser or download the PDF.

Modular Arithmetic, GCD and the Extended Euclidean Algorithm

The world of remainders: the computational foundation of modern cryptography

Slides: 25 PDF · 1000 KB
Primes, Euler's Totient, Fermat's and Euler's Theorems

The number-theory foundation of asymmetric cryptography: how we find large primes and why they provide security.

Slides: 24 PDF · 1.1 MB

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge