Modular Arithmetic
Modular arithmetic is "clock arithmetic": numbers wrap around after reaching a fixed size, the modulus. Five hours after 10 o'clock is 3 o'clock, not 15. In code this is the % operator, and it shows up in game loops, ring buffers, hash tables, calendars and cryptography. This lesson covers the basic rules, the trap with negative numbers, and the most common programming patterns.
The remainder, revisited
In Division and Remainders you wrote . Modular arithmetic keeps only the remainder:
For a modulus , the result is always one of . Two numbers are congruent modulo when they leave the same remainder. We write : they all sit at the same position on a 5-hour clock.
The clock picture in code, with hours 0–23 and weekdays 0–6:
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print("22:00 + 5 h ->", (22 + 5) % 24, ":00")
print("Thursday + 10 days ->", DAYS[(3 + 10) % 7])
print("17 mod 5 =", 17 % 5, " divmod:", divmod(17, 5))
print([n % 4 for n in range(10)])22:00 + 5 h -> 3 :00
Thursday + 10 days -> Sun
17 mod 5 = 2 divmod: (3, 2)
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1]
Rules that make it useful
You can reduce before or after adding, subtracting or multiplying and get the same remainder:
So you never need huge numbers to find a remainder. What is the last digit of ? Work mod 10: , and then it repeats every 4 steps. Since , the last digit is 1. Python's three-argument pow(base, exp, mod) uses the same idea to stay fast:
print(pow(7, 100, 10))
print([pow(7, k, 10) for k in range(1, 9)])
print(pow(3, 10**6, 1_000_007)) # instant, no million-digit number
print((123456 * 789012) % 97, ((123456 % 97) * (789012 % 97)) % 97)1
[7, 9, 3, 1, 7, 9, 3, 1]
81323
38 38
Note: Division does not work this simply. "Dividing" mod means multiplying by a modular inverse, which exists only when the number shares no factor with . That is a topic for the planned Number Theory & Cryptography course.
Negative numbers: Python vs C
What is ? Mathematicians answer 2, because . Languages disagree:
| Expression | Python | C, C++, Java, JavaScript, Go, Rust |
|---|---|---|
-7 % 3 |
2 | −1 |
7 % -3 |
−2 | 1 |
-7 / 3 (integer) |
-7 // 3 = −3 (floor) |
−2 (toward zero) |
Python's % takes the sign of the divisor, so with a positive modulus you always get . C-family languages truncate the quotient toward zero, so the remainder takes the sign of the dividend. Both satisfy a == (a // n) * n + a % n with their own kind of division. In C, write ((a % n) + n) % n to get the mathematical result. Python's math.fmod behaves like C:
import math
print(-7 % 3, -7 // 3)
print(math.fmod(-7, 3), int(-7 / 3)) # C-style: truncate toward zero
c_style = -1
print("fix:", (c_style + 3) % 3)
print("step back from index 0:", (0 - 1) % 5)2 -3
-1.0 -2
fix: 2
step back from index 0: 4
In software
- Wrapping indexes. Moving "left" from slot 0 of a 5-slot carousel goes to slot 4:
(i - 1) % n. In Python this is safe. In JavaScript or C you need(i - 1 + n) % n. - Game loops. "Do something every 60 frames" is
if frame % 60 == 0. Animation frames cycle withframe % len(frames). Pac-Man-style screens wrap withx % width. - Ring buffers. A fixed-size queue writes at
head = (head + 1) % capacity, overwriting the oldest entry. Logs, audio buffers and network queues use this. - Hash tables pick a bucket with
hash(key) % num_buckets(see Hash Tables). - Check digits. ISBN, IBAN and credit card (Luhn) checks are sums taken mod 10, 11 or 97.
- Cryptography. RSA and Diffie–Hellman are built on
pow(g, secret, p)with enormous moduli. - Fixed-width integers are arithmetic mod (see Integer Overflow and Two's Complement).
class RingBuffer:
def __init__(self, capacity):
self.data = [None] * capacity
self.head = 0 # next slot to write
def push(self, item):
self.data[self.head] = item
self.head = (self.head + 1) % len(self.data)
buf = RingBuffer(4)
for reading in [10, 11, 12, 13, 14, 15]:
buf.push(reading)
print(buf.data, "head =", buf.head)
buckets = 8
for word in ["cat", "dog", "owl"]:
print(word, "-> bucket", sum(map(ord, word)) % buckets)[14, 15, 12, 13] head = 2
cat -> bucket 0
dog -> bucket 2
owl -> bucket 2
The toy hash adds the character codes (ord). "dog" and "owl" land in the same bucket, a collision, which every hash table must handle. Python's own hash() of a string changes between runs, so it is not used here.
Exercises
Exercise 1: Clock arithmetic
It is 9:00 on a 24-hour clock. What time is it 100 hours later, and what weekday if it is now Tuesday?
Answer
13:00, on Saturday.
Solution
days, hour = divmod(9 + 100, 24)
print(days, hour, ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][(1 + days) % 7])4 13 Sat
Exercise 2: Last digit by hand
Find the last digit of without a calculator.
Answer
9
Solution
Work mod 10 and look for a cycle:
print(pow(3, 2026, 10))9
Exercise 3: Negative remainders
Give the result of -13 % 5 in Python and in C, and the formula that makes C give Python's answer.
Answer
Python: 2. C: −3. Fix in C: ((a % n) + n) % n.
Solution
Python (floor): −13 = −3·5 + 2 → 2
C (toward zero): −13 = −2·5 + (−3) → −3
fix: ((−3) + 5) % 5 = 2Exercise 4: Every n-th frame
A game runs at 60 frames per second. Write a loop over frames 0–299 that prints the frame number whenever a 1.5-second timer fires (frame 0 included), and the animation frame frame % 4 at those moments.
Answer
The timer fires at frames 0, 90, 180 and 270, with animation frames 0, 2, 0, 2.
Solution
, so the timer fires when frame % 90 == 0. Then , and .
for frame in range(300):
if frame % 90 == 0:
print(frame, frame % 4)0 0
90 2
180 0
270 2
Test yourself
What is ?
- 3
- 4
- 5
- 6
What does Python print for -1 % 8?
- -1
- 1
- 7
- An error
A ring buffer has capacity 5 and . Where does the next write go after this one?
- Slot 5
- Slot 0
- Slot 4 again
- Slot 1