Skip to content

Modular Arithmetic

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

Your turn

What does this print?

print((17 + 9) % 7)

Mini quiz

1 / 3

What is (45 + 31) % 12?