AlgoViz

Modular arithmetic

easy 14 min

Modular arithmetic is clock maths: numbers wrap back to 0 after reaching the modulus.

Where it shows up

The same pattern appears across everyday software.

  • Hash maps and sets

    Python dicts, Java HashMaps and database hash indexes all finish by reducing a hash to a bucket number, either with mod or with a bit mask when the table size is a power of two.

  • Ring buffers

    Audio and video streaming, network packet queues, keyboard event buffers and in-memory logs keep a fixed array and advance read and write positions with (i + 1) % size, overwriting the oldest data.

  • Cryptography

    RSA, Diffie-Hellman and elliptic-curve schemes are built on arithmetic modulo very large numbers, and they rely on fast modular exponentiation to raise values to exponents hundreds of digits long.

  • Check digits

    ISBN-10 uses a weighted sum mod 11, and credit card numbers use the Luhn check, a sum mod 10, so a single mistyped digit is caught before anything is sent.

  • Calendars and schedules

    Day-of-week calculations, cron schedules and round-robin load balancing (request n goes to server n % k) are all modular arithmetic on a cycle.

  • Competitive programming

    Counting problems ask for answers modulo 10^9 + 7 so results fit in fixed-size integers; contestants reduce after every step and use modular inverses for division.