AlgoViz

Modular arithmetic

easy 14 min

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

See it run

Watch 25 wrap to 1 on a 12-hour clock, index 7 land on C in a 5-slot ring, key 42 drop into bucket 2, and 3^5 mod 7 come out as 5 in three squarings.

Operations

Clock Arithmetic

The classic picture of mod: a clock wraps back to 0 after its last position. $25 \bmod 12 = 1$ because 25 steps is two full laps and one step more.

Step 1 of 7

Start: 25 mod 12

01234567891011

Think of a clock with 12 positions, 0 to 11. The hand starts at 0 and must move 25 steps forward, wrapping round whenever it passes 11. Where it stops is 25 \bmod 12.

Step 1: Start: 25 mod 12

def clock_mod(n, m):    laps = n // m             # full trips round the clock    left = n - laps * m       # steps after the last full lap    return laps, left         # same as divmod(n, m)print(clock_mod(25, 12))      # (2, 1): 25 = 2 * 12 + 1print(25 % 12)                # 1print((9 + 5) % 12)           # 2: 9 o'clock plus 5 hoursprint(-3 % 12)                # 9: Python counts backwards round the clock
Time
O(1)
Space
O(1)
walking step by step
O(n)
divmod(25, 12)
(2, 1)

Whenever something wraps after a fixed count (hours, days of the week, seats in a circle), the position after n moves is start plus n, mod the count.

In the real world

The same modular arithmetic doing real jobs. Pick one and step through it.

Days repeat every 7. Today is Wednesday (day 3, counting Sunday as 0). What day is it 100 days from now?

Step 1 of 3

Today is day 3

0123456

Sun 0, Mon 1, Tue 2, Wed 3, Thu 4, Fri 5, Sat 6

Number the days Sunday = 0 to Saturday = 6. Today is Wednesday, day 3.

Step 1: Today is day 3

today = 3                        # Wednesdayprint((today + 100) % 7)         # 5, Friday

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Assuming % is never negative

    critical

    In C, C++, Java, JavaScript and Go the result takes the sign of the dividend, so -3 % 5 is -3. Used as an array index it crashes or reads the wrong slot. Python returns 2, which hides the bug until the code is ported.

    Wrong
    // Java or JavaScriptint prev = (i - 1) % n;      // -1 when i == 0
    Right
    // works in every languageint prev = (i - 1 + n) % n;int safe = ((x % n) + n) % n;
  • Reducing only at the end

    critical

    Multiplying first and taking mod at the end lets intermediate values overflow 64 bits in most languages, and in Python it makes numbers huge and slow. Reduce after every operation.

    Wrong
    result = 1for i in range(2, n + 1):    result *= ireturn result % MOD          # result has thousands of digits
    Right
    result = 1for i in range(2, n + 1):    result = (result * i) % MOD   # stays below MODreturn result
  • Subtracting without adding the modulus back

    major

    Both values are already reduced, but a - b can still be negative. In languages with a sign-of-dividend %, (a - b) % m then stays negative.

    Wrong
    diff = (a % MOD - b % MOD) % MOD    # can be negative in C++/Java
    Right
    diff = (a % MOD - b % MOD + MOD) % MOD
  • Dividing under a modulus

    major

    Mod does not distribute over division: (a / b) mod m is not (a mod m) / (b mod m). Multiply by the modular inverse instead, which for a prime m is b^(m-2) mod m.

    Wrong
    ans = (a % MOD) // (b % MOD)
    Right
    inv_b = pow(b, MOD - 2, MOD)      # MOD is primeans = (a % MOD) * inv_b % MOD
  • Writing 1e9+7 as the modulus

    minor

    In Python 1e9 + 7 is the float 1000000007.0, so % returns floats and loses precision on large values. Use the integer 10**9 + 7.

    Wrong
    MOD = 1e9 + 7          # a floatprint(10**18 % MOD)    # float result, digits lost
    Right
    MOD = 10**9 + 7        # an intprint(10**18 % MOD)    # exact
  • Using % 0

    minor

    Mod by zero is undefined: Python raises ZeroDivisionError. Guard empty containers before writing i % len(arr).

    Wrong
    item = arr[i % len(arr)]   # crashes when arr is empty
    Right
    item = arr[i % len(arr)] if arr else None

Interview tips

  • Spot it fast

    • Anything that wraps: clocks, weekdays, circular queues, rotating turns.
    • "Return the answer modulo 10^9 + 7" means reduce after every step.
    • Hashing a key into a fixed number of slots.
    • Even or odd, last digit, divisibility: n % 2, n % 10, n % k == 0.
  • Rules to know cold

    • (a + b) mod m and (a × b) mod m can be reduced at every step.
    • For subtraction add m back: (a - b + m) mod m.
    • Division needs a modular inverse; for prime p it is a^(p-2) mod p.
    • Fast power: O(log e) multiplications, one per bit of the exponent.
  • Say it in the interview

    • "I reduce after each multiply so every intermediate stays below MOD squared, which fits in 64 bits."
    • "Python's % follows the divisor's sign; in Java I would add n before taking mod."
    • Mention that 10^9 + 7 is prime, so division by inverse works.
  • Traps

    • -3 % 5 is 2 in Python but -3 in C, Java and JavaScript.
    • 1e9 + 7 is a float in Python; write 10**9 + 7.
    • Patterned keys with a table size that shares their pattern pile into a few buckets.