Modular Arithmetic
Modular arithmetic is arithmetic with remainders: clock time, days of the week, angles, and every fixed-width integer in a CPU. Gauss introduced the notation , and with it you can add, subtract and multiply remainders as if they were ordinary numbers. For a school-level introduction see Modular Arithmetic in Basic Math.
Congruence
For an integer , is congruent to modulo ,
Equivalently, and leave the same remainder when divided by : . Examples: (5 o'clock), , .
Congruence modulo is an equivalence relation: reflexive, symmetric and transitive. It splits into residue classes, represented by .
Arithmetic is compatible
Theorem. If and , then
Proof for products. , and divides both terms.
So you can reduce at any time. This is what makes huge computations feasible: to find the last two digits of , work modulo 100 and never handle a number bigger than .
def powmod(a, e, n):
"""Repeated squaring, reducing modulo n after every multiplication."""
result, a = 1, a % n
while e:
if e & 1:
result = result * a % n
a = a * a % n
e >>= 1
return result
print("7^2026 mod 100 =", powmod(7, 2026, 100), " built-in:", pow(7, 2026, 100))
print("last digits of 7^2026 by full computation:", str(7 ** 2026)[-2:])
print("digits in 7^2026:", len(str(7 ** 2026)))7^2026 mod 100 = 49 built-in: 49
last digits of 7^2026 by full computation: 49
digits in 7^2026: 1713
The fast version needs about squarings; the full number has 1713 digits. RSA computes for 2048-bit and in exactly this way.
Division is the exception
Cancellation fails in general: (both are 6 or 16, remainder 6), but . You may cancel a factor only when . The multiplication tables show why: modulo 10, multiplying by 2 is not a bijection, but multiplying by 3 is.
n = 10
for k in [2, 3, 5, 7]:
row = [k * x % n for x in range(n)]
print(f"{k} * x mod {n}: {row} bijection: {sorted(row) == list(range(n))}")2 * x mod 10: [0, 2, 4, 6, 8, 0, 2, 4, 6, 8] bijection: False
3 * x mod 10: [0, 3, 6, 9, 2, 5, 8, 1, 4, 7] bijection: True
5 * x mod 10: [0, 5, 0, 5, 0, 5, 0, 5, 0, 5] bijection: False
7 * x mod 10: [0, 7, 4, 1, 8, 5, 2, 9, 6, 3] bijection: True
Rows for 3 and 7 are permutations of , so each has a 1 somewhere: . Rows for 2 and 5 never reach 1. When is prime, every nonzero is coprime to , so every nonzero number has an inverse: is a field. (See also Matrices mod p.)
The set with and taken modulo satisfies the familiar rules: associativity, commutativity, distributivity, identities 0 and 1. That is why a 32-bit CPU computes correctly in : unsigned overflow is not an error, it is arithmetic modulo .
In software
- Hashing:
h = (h * 31 + ord(c)) % Mprocesses a string with all intermediate values bounded. - Circular buffers and round-robin:
(i + 1) % n. - Calendars: the weekday of a date is computed modulo 7 (Zeller's congruence).
- Checksums: ISBN-10 uses mod 11, IBAN uses mod 97.
- Integer overflow in C, Java and Rust's wrapping types is arithmetic in or .
Exercises
Exercise 1: Congruent or not?
(a) ? (b) ? (c) ?
Answer
(a) yes; (b) yes; (c) yes.
Solution
(a) . (b) . (c) .
Exercise 2: Last digit by hand
Find the last digit of .
Answer
Solution
, so
Exercise 3: Day of the week
Today is a Wednesday. What day is it days from now?
Answer
Thursday.
Solution
, so (). So days is a whole number of weeks plus one day: one day after Wednesday is Thursday.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(10 ** 6 % 7, days[(days.index("Wed") + 10 ** 6) % 7])1 Thu
Exercise 4: 32-bit overflow
A 32-bit unsigned counter holds and is increased by 10. What value does it hold?
Answer
Solution
.
Test yourself
means…
Which number has a multiplicative inverse modulo 12?
- 4
- 6
- 8
- 5
Why can RSA compute quickly for enormous ?
- By computing exactly first
- By repeated squaring with reduction mod after each step
- Because is always small
- It cannot