TExcelTAD
Home › Basic Math & Pre-Algebra › Modular Arithmetic

Modular Arithmetic

Modular arithmetic is "clock arithmetic": numbers wrap around after reaching a fixed size, the modulus. Five hours after 10 o'clock is 3 o'clock, not 15. In code this is the % operator, and it shows up in game loops, ring buffers, hash tables, calendars and cryptography. This lesson covers the basic rules, the trap with negative numbers, and the most common programming patterns.

The remainder, revisited

In Division and Remainders you wrote 17÷5=3 remainder 217 \div 5 = 3\ \text{remainder}\ 2. Modular arithmetic keeps only the remainder:

17 mod 5=2because 17=3⋅5+217 \bmod 5 = 2 \qquad \text{because } 17 = 3 \cdot 5 + 2

For a modulus nn, the result is always one of 0,1,…,n−10, 1, \ldots, n - 1. Two numbers are congruent modulo nn when they leave the same remainder. We write 17≡2≡22≡−3(mod5)17 \equiv 2 \equiv 22 \equiv -3 \pmod{5}: they all sit at the same position on a 5-hour clock.

The clock picture in code, with hours 0–23 and weekdays 0–6:

python · try it yourself
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

print("22:00 + 5 h ->", (22 + 5) % 24, ":00")
print("Thursday + 10 days ->", DAYS[(3 + 10) % 7])
print("17 mod 5 =", 17 % 5, "  divmod:", divmod(17, 5))
print([n % 4 for n in range(10)])
22:00 + 5 h -> 3 :00
Thursday + 10 days -> Sun
17 mod 5 = 2   divmod: (3, 2)
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1]

Rules that make it useful

You can reduce before or after adding, subtracting or multiplying and get the same remainder:

(a+b) mod n=((a mod n)+(b mod n)) mod n(a⋅b) mod n=((a mod n)⋅(b mod n)) mod n\begin{aligned} (a + b) \bmod n &= ((a \bmod n) + (b \bmod n)) \bmod n \\ (a \cdot b) \bmod n &= ((a \bmod n) \cdot (b \bmod n)) \bmod n \end{aligned}

So you never need huge numbers to find a remainder. What is the last digit of 71007^{100}? Work mod 10: 7,49→9,63→3,21→17, 49 \to 9, 63 \to 3, 21 \to 1, and then it repeats every 4 steps. Since 100=4⋅25100 = 4 \cdot 25, the last digit is 1. Python's three-argument pow(base, exp, mod) uses the same idea to stay fast:

python · try it yourself
print(pow(7, 100, 10))
print([pow(7, k, 10) for k in range(1, 9)])
print(pow(3, 10**6, 1_000_007))     # instant, no million-digit number
print((123456 * 789012) % 97, ((123456 % 97) * (789012 % 97)) % 97)
1
[7, 9, 3, 1, 7, 9, 3, 1]
81323
38 38

Note: Division does not work this simply. "Dividing" mod nn means multiplying by a modular inverse, which exists only when the number shares no factor with nn. That is a topic for the planned Number Theory & Cryptography course.

Negative numbers: Python vs C

What is −7 mod 3-7 \bmod 3? Mathematicians answer 2, because −7=−3⋅3+2-7 = -3 \cdot 3 + 2. Languages disagree:

Expression Python C, C++, Java, JavaScript, Go, Rust
-7 % 3 2 −1
7 % -3 −2 1
-7 / 3 (integer) -7 // 3 = −3 (floor) −2 (toward zero)

Python's % takes the sign of the divisor, so with a positive modulus you always get 0…n−10 \ldots n - 1. C-family languages truncate the quotient toward zero, so the remainder takes the sign of the dividend. Both satisfy a == (a // n) * n + a % n with their own kind of division. In C, write ((a % n) + n) % n to get the mathematical result. Python's math.fmod behaves like C:

python · try it yourself
import math

print(-7 % 3, -7 // 3)
print(math.fmod(-7, 3), int(-7 / 3))   # C-style: truncate toward zero
c_style = -1
print("fix:", (c_style + 3) % 3)
print("step back from index 0:", (0 - 1) % 5)
2 -3
-1.0 -2
fix: 2
step back from index 0: 4

In software

  • Wrapping indexes. Moving "left" from slot 0 of a 5-slot carousel goes to slot 4: (i - 1) % n. In Python this is safe. In JavaScript or C you need (i - 1 + n) % n.
  • Game loops. "Do something every 60 frames" is if frame % 60 == 0. Animation frames cycle with frame % len(frames). Pac-Man-style screens wrap with x % width.
  • Ring buffers. A fixed-size queue writes at head = (head + 1) % capacity, overwriting the oldest entry. Logs, audio buffers and network queues use this.
  • Hash tables pick a bucket with hash(key) % num_buckets (see Hash Tables).
  • Check digits. ISBN, IBAN and credit card (Luhn) checks are sums taken mod 10, 11 or 97.
  • Cryptography. RSA and Diffie–Hellman are built on pow(g, secret, p) with enormous moduli.
  • Fixed-width integers are arithmetic mod 2n2^n (see Integer Overflow and Two's Complement).
python · try it yourself
class RingBuffer:
    def __init__(self, capacity):
        self.data = [None] * capacity
        self.head = 0                      # next slot to write

    def push(self, item):
        self.data[self.head] = item
        self.head = (self.head + 1) % len(self.data)

buf = RingBuffer(4)
for reading in [10, 11, 12, 13, 14, 15]:
    buf.push(reading)
print(buf.data, "head =", buf.head)

buckets = 8
for word in ["cat", "dog", "owl"]:
    print(word, "-> bucket", sum(map(ord, word)) % buckets)
[14, 15, 12, 13] head = 2
cat -> bucket 0
dog -> bucket 2
owl -> bucket 2

The toy hash adds the character codes (ord). "dog" and "owl" land in the same bucket, a collision, which every hash table must handle. Python's own hash() of a string changes between runs, so it is not used here.

Exercises

Exercise 1: Clock arithmetic

It is 9:00 on a 24-hour clock. What time is it 100 hours later, and what weekday if it is now Tuesday?

Answer

13:00, on Saturday.

Solution
9+100=109 hours since midnight Tuesday109=4⋅24+13→ 13:00, four days laterTuesday+4 days→ Saturday\begin{aligned} &9 + 100 = 109\ \text{hours since midnight Tuesday} \\ &109 = 4 \cdot 24 + 13 && \to\ \text{13:00, four days later} \\ &\text{Tuesday} + 4\ \text{days} && \to\ \text{Saturday} \end{aligned}
python · try it yourself
days, hour = divmod(9 + 100, 24)
print(days, hour, ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][(1 + days) % 7])
4 13 Sat

Exercise 2: Last digit by hand

Find the last digit of 320263^{2026} without a calculator.

Answer

9

Solution

Work mod 10 and look for a cycle:

31→3, 32→9, 33→27→7, 34→21→1, then 3,9,7,1 repeats2026=4⋅506+2, so 32026 ends like 32, which is 9\begin{aligned} &3^1 \to 3,\ 3^2 \to 9,\ 3^3 \to 27 \to 7,\ 3^4 \to 21 \to 1,\ \text{then } 3, 9, 7, 1 \text{ repeats} \\ &2026 = 4 \cdot 506 + 2,\ \text{so } 3^{2026} \text{ ends like } 3^2,\ \text{which is } 9 \end{aligned}
python · try it yourself
print(pow(3, 2026, 10))
9

Exercise 3: Negative remainders

Give the result of -13 % 5 in Python and in C, and the formula that makes C give Python's answer.

Answer

Python: 2. C: −3. Fix in C: ((a % n) + n) % n.

Solution
text
Python (floor):     −13 = −3·5 + 2    → 2
C (toward zero):    −13 = −2·5 + (−3) → −3
fix: ((−3) + 5) % 5 = 2

Exercise 4: Every n-th frame

A game runs at 60 frames per second. Write a loop over frames 0–299 that prints the frame number whenever a 1.5-second timer fires (frame 0 included), and the animation frame frame % 4 at those moments.

Answer

The timer fires at frames 0, 90, 180 and 270, with animation frames 0, 2, 0, 2.

Solution

1.5 s×60 frames/s=90 frames1.5\ \text{s} \times 60\ \text{frames/s} = 90\ \text{frames}, so the timer fires when frame % 90 == 0. Then 90 mod 4=290 \bmod 4 = 2, 180 mod 4=0180 \bmod 4 = 0 and 270 mod 4=2270 \bmod 4 = 2.

python · try it yourself
for frame in range(300):
    if frame % 90 == 0:
        print(frame, frame % 4)
0 0
90 2
180 0
270 2

Test yourself

What is 38 mod 738 \bmod 7?

  1. 3
  2. 4
  3. 5
  4. 6

What does Python print for -1 % 8?

  1. -1
  2. 1
  3. 7
  4. An error

A ring buffer has capacity 5 and head=4\text{head} = 4. Where does the next write go after this one?

  1. Slot 5
  2. Slot 0
  3. Slot 4 again
  4. Slot 1