Modular Arithmetic: The Math Behind Clocks, Hashing, and Cryptography
Every clock on the wall is already running a program in modular arithmetic -- and so is every hash table and every encryption scheme.
Look at the clock on your wall. When the hour hand passes 12, it doesn't keep counting up to 13, 14, 15 -- it wraps back around to 1. That wraparound is modular arithmetic in its purest form: a system where numbers reset to zero (or one, depending on how you're counting) once they hit a fixed limit called the modulus. If someone asks what time it is 5 hours after 10:00, you don't answer "15:00" -- you answer "3:00," because on a 12-hour clock, 15 wraps around to 3.
The formal name for that wraparound is "mod," and it just means the remainder left over after division. Fifteen mod twelve is three, because twelve divides into fifteen once with three left over. Once you see mod as "the remainder," plenty of everyday code clicks into place: alternating the color of table rows by checking whether a row's index mod 2 equals 0, or cycling through a fixed set of colors by looping an index back to zero once it runs past the end of the list.
Hash tables lean on the exact same trick. A hash function turns something arbitrary -- a username, a file path -- into a number, and that number gets reduced with mod against the size of the table's underlying array so it always lands on a valid slot, no matter how enormous the original number was. That's also why resizing a hash table is disruptive: changing the array's size changes the modulus, so most existing entries have to be rehashed into new slots.
Cryptography pushes modular arithmetic somewhere more interesting: making it hard to run backward. RSA encryption, one of the foundational tools for securing web traffic, raises numbers to large powers and then takes the remainder against a modulus built from two enormous prime numbers. Computing that result is fast; given only the result, working backward to the original number without knowing those two primes is, with current computers, essentially impossible. That one-way-easy, other-way-brutal asymmetry is the entire basis for public-key encryption -- the padlock icon in a browser's address bar.
So the same wraparound that keeps a clock honest after 12:00 is quietly running underneath cache eviction policies, the check digit on a credit card number, and the encryption protecting a bank transfer. It's a rare case where the toy example you learned as a kid and the production system securing real money are, structurally, doing the identical operation.
