Modular Arithmetic

Difficulty
Importance

The problem

Many systems need values that wrap around (ring buffers, clock hours) or that must be spread evenly across a fixed number of buckets (hash tables). Modular arithmetic is the algebra of remainders — it gives wraparound and bucketing a principled, composable definition instead of ad hoc rules.

Why now

Number systems and bases gives positional representation, but not the algebra of what happens when a count exceeds its representation's range. Without modular arithmetic, 'hash this key into one of N buckets' has no formal definition — you'd be inventing a rule instead of applying one with known, provable properties like (a+b) mod n = ((a mod n)+(b mod n)) mod n.

Mental model

Modular arithmetic is clock arithmetic — once you reach the modulus you wrap back to zero. '17 mod 5' asks 'how far past the last full wrap am I?' Once hashing, cyclic buffers, and calendar math are all seen as this one wraparound idea, each stops being a special case you memorize separately.

Requires

Helps

Unlocks

Related

Used in

Projects

  • Implement a fixed-size circular buffer using only modular arithmetic for index wraparound
  • Implement a simple hash table and measure bucket-fill distribution as you vary the modulus

Examples

  • A ring buffer of size 8: writing at index 7 then advancing goes to index 0, i.e. (7+1) mod 8
  • Consistent hashing places servers and keys on a mod-n ring so only a fraction of keys remap when a server is added

Resources

Mastery checklist