Modular arithmetic
easy 14 minModular arithmetic is clock maths: numbers wrap back to 0 after reaching the modulus.
Video lesson · Chapter 1 of 7
The recorder that keeps running
Five Slots — Modular Arithmetic
1:25Reel
Read caption
Where does sample 17 go in five slots? 17 = 3 × 5 + 2. The three full laps bring the writer back to the start. The two remaining steps put it at slot 2, where sample 12 is now the oldest reading. Try the next one before you replay the ending. Which slot does sample 18 write to?
How it works
Step through the idea, or press Play.
Divide and keep the remainder. 25 mod 12 asks what is left after taking out as many 12s as fit: 25 = 2 × 12 + 1, so the answer is 1
Understand it
Start here
What mod means
The modulo operation gives the remainder after division. Writing a % m asks: when you take as many whole copies of out of as you can, what is left over? , because . Programmers call it clock maths: the numbers wrap back to 0 once they reach .
The division identity
a // m) and is the remainder (Python a % m). So gives .Dividend
The number you start with, such as 25 hours or index 7.
Modulus
The size of the cycle: 12 hours, 5 array slots, 10 buckets.
Quotient
How many full laps fit. Full laps change nothing about where you end up.
Remainder
Where you land: always one of . This is the answer.
The picture
Clock arithmetic: 25 mod 12
On a 12-hour clock, hour 25 is hour 1. Start the hand at 0 and move 25 steps: the first 12 bring it back to 0, the next 12 bring it back again, and one step is left over. The full laps are the quotient; the leftover steps are the remainder.
Step by step: 25 mod 12
- 1
Divide
remainder 1. The quotient is 2.
- 2
Remove full cycles
steps are two complete rotations, which bring the hand back to 0.
- 3
Keep the leftover
. The hand lands on 1, and that is the answer.
Computing a mod m by laps
a % m does it in a single O(1) instruction.Notation
Congruence: same remainder, same place
Two numbers that leave the same remainder sit on the same spot of the clock. Mathematicians write this as a congruence: , read "25 is congruent to 1 mod 12". Equivalently, their difference is a multiple of .
Definition of congruence
| Congruence | Why | Where you meet it |
|---|---|---|
| Hour 25 is 1 o'clock | ||
| Index 7 of a 5-slot ring is slot 2 | ||
| Key 42 in 10 buckets goes to bucket 2 | ||
| divides | n % 2 == 0 is the even test | |
Why Python says -3 % 5 == 2 |
arr[0] = arr[5] = arr[10] in a circular array of size 5, because 0, 5 and 10 are all congruent mod 5.The rules
Reduce at every step
Addition and multiplication
Subtraction: add m back
| Operation | Reduce as you go? | How |
|---|---|---|
| Addition | Yes | (a + b) % m |
| Subtraction | Yes, add back | (a - b + m) % m |
| Multiplication | Yes | (a * b) % m, each factor already below |
| Power | Yes, by squaring | pow(a, e, m), O(log e) |
| Division | No | Multiply by the inverse: when is prime |
Gotcha
Negative numbers depend on the language
Mod of a negative number is a classic interview trap. Python rounds the quotient down (floor division), so the remainder takes the sign of the divisor: -3 % 5 is 2. C, C++, Java, JavaScript and Go round toward zero, so the remainder takes the sign of the dividend: -3 % 5 is -3.
| Expression | Python | C / C++ / Java / JavaScript | Rule |
|---|---|---|---|
-3 % 5 | 2 | -3 | floor vs truncate |
3 % -5 | -2 | 3 | sign of divisor vs dividend |
-10 % 3 | 2 | -1 | vs |
((-3 % 5) + 5) % 5 | 2 | 2 | safe everywhere |
math.fmod(-3, 5) gives the C-style -3.0 if you ever need it.Getting a safe remainder in any language
((n % m) + m) % m.import mathprint(-3 % 5) # 2 Python: sign of the divisorprint(math.fmod(-3, 5)) # -3.0 C-style truncationprint(((-3 % 5) + 5) % 5) # 2 the portable patternprint((0 - 1) % 5) # 4 stepping back from index 0Wrap-around
Circular arrays and ring buffers
A circular array treats the end as joined to the start, so index means slot . Index 7 in an array of size 5 is slot . Moving a pointer forward is i = (i + 1) % n: from the last slot it jumps straight back to 0, with no if.
A ring buffer of size 4 receiving a fifth item
(head + count) % size. Once full, each push overwrites the oldest item and moves the head on.class RingBuffer: def __init__(self, size): self.buf = [None] * size self.size = size self.head = 0 # index of the oldest item self.count = 0 def push(self, item): self.buf[(self.head + self.count) % self.size] = item if self.count < self.size: self.count += 1 else: # full: the oldest item was overwritten self.head = (self.head + 1) % self.size def get(self, i): # i = 0 is the oldest item kept return self.buf[(self.head + i) % self.size]rb = RingBuffer(3)for x in [1, 2, 3, 4]: rb.push(x)print([rb.get(i) for i in range(rb.count)]) # [2, 3, 4]Circular queue
Front and rear move with
(i + 1) % capacity, so a fixed array never needs shifting.Streaming buffers
Audio, network packets and keyboard events overwrite the oldest data in a ring.
Rotate an array
Item at moves to when rotating right by .
Hashing
Hash tables: the bucket assignment
Hash functions return huge numbers, but a table only has buckets numbered 0 to . The last step is always . Key 42 in 10 buckets lands in bucket 2. Java's "hello".hashCode() is 99162322, and .
- 1Key42 or "hello"
- 2Hasha large integer
- 3mod msqueezes it into 0..m-1
- 4Bucketstore or look up here
Lookups repeat the same calculation and jump straight to the bucket: O(1) on average.
| Keys | mod 10 | mod 7 (prime) |
|---|---|---|
| 10, 20, 30, 40, 50 | 0, 0, 0, 0, 0: one long chain | 3, 6, 2, 5, 1: spread out |
| 42, 17, 52, 99, 7 | 2, 7, 2, 9, 7: two collisions | 0, 3, 3, 1, 0 |
Big numbers
Overflow and the 10⁹ + 7 trick
Counting problems produce enormous answers: has 158 digits, far beyond a 64-bit integer. So problems ask for the answer modulo $10^9 + 7$. Because of the rules above you can reduce after every addition or multiplication and still get exactly the right remainder, while every intermediate stays small.
Why the products still fit in 64 bits
Why exactly 10^9 + 7
Large
About a billion possible remainders, so different answers rarely collide by chance.
Prime
Every non-zero value has an inverse, so division works via .
Safe
Products of two reduced values fit in 64 bits; sums fit in 32 bits.
MOD = 10**9 + 7 # an int; 1e9 + 7 would be a floatdef factorial_mod(n): result = 1 for i in range(2, n + 1): result = (result * i) % MOD return resultprint(factorial_mod(100)) # 437918130print(pow(3, MOD - 2, MOD)) # 333333336, the inverse of 3print(3 * pow(3, MOD - 2, MOD) % MOD) # 1Fast power
Modular exponentiation
To compute for a huge , do not multiply times. Read the exponent in binary: square the base once per bit, and multiply it into the result only where the bit is 1. Reduce after every multiply. For : , so .
Square and multiply
The fast power loop
def mod_pow(base, exp, m): result = 1 base %= m while exp > 0: if exp % 2 == 1: result = (result * base) % m base = (base * base) % m exp //= 2 return resultprint(mod_pow(3, 5, 7), pow(3, 5, 7)) # 5 5print(mod_pow(2, 10**18, 10**9 + 7)) # 719476260, instantlyPattern spotting
When to reach for mod
Does this problem want mod?
| Pattern | Meaning |
|---|---|
n % 2 == 0 / n % 2 == 1 | Even or odd check |
i % len(arr) | Circular indexing |
(head + i) % size | Ring buffer access |
hash(key) % buckets | Hash table index |
(a + b) % m, (a * b) % m | Modular addition and multiplication |
((n % m) + m) % m | Safe negative mod in any language |
result % (10**9 + 7) | Keep huge answers small |
n % 10, n //= 10 | Peel off decimal digits |
Safe habits
- Reduce after every
+,-and*when a modulus is given. - Add
mback before taking mod of a difference. - Use
pow(b, e, m)or square-and-multiply for powers. - Write
MOD = 10**9 + 7as an integer constant.
Common slips
- Taking mod only at the very end, after values have overflowed.
- Trusting
-3 % 5to be 2 in Java or JavaScript. - Dividing reduced values instead of multiplying by an inverse.
- Writing
1e9 + 7, which is a float in Python.
Recap
Key takeaways
Key points
- is the remainder in , always between 0 and .
- Think of a clock: full laps vanish, only the leftover steps count. .
- means and leave the same remainder; divides .
- Reduce at every step for addition, subtraction (add back) and multiplication; division needs an inverse.
- Python's
-3 % 5is 2; C, Java and JavaScript give -3. Portable fix:((n % m) + m) % m. arr[i % n]wraps indexes;hash(key) % mpicks a bucket;(i + 1) % nmoves a ring pointer.- is prime and small enough that products of reduced values fit in 64 bits.
- Fast power computes in O(log e) multiplications.