Modular Arithmetic
Math & Number Theory: lesson 1 of 5
A remainder is a position on a clock, not a leftover.
Lesson 1 of 5 · 4 min
Modular Arithmetic
Step 1 of 9
A clock has twelve positions. Step past 11 and you are back at 0 — that wrap is the whole of modular arithmetic.
The Idea
A clock has twelve positions. Step past 11 and you are back at 0, so 45 and 9 land in the same place.
That is all % does: it reports where you stopped, never how many laps you ran. Add, subtract or multiply first, or reduce first — the position is the same.
Real-World Example
Every hash table does this. A hash is a huge arbitrary integer, and hash % buckets turns it into a slot number that actually exists. Ring buffers, retry backoffs and cryptography lean on the same trick: reduce as you go, and the numbers never grow.
The Code
m = 12
print((45 + 31) % m) # 4 -> six laps and four
print(((45 % m) + (31 % m)) % m) # 4 -> reduce first, same landing
print((9 * 7) % m) # 3 -> multiplication survives too
print(-3 % m) # 9 -> Python never answers negativeYour turn
What does this print?
print((17 + 9) % 7)Mini quiz
1 / 3