AlgoViz

Modular arithmetic

easy 14 min

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

Video lesson · Chapter 1 of 7

The recorder that keeps running

0:00 / 6:02

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.

Step 1 of 3

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 mm out of aa as you can, what is left over? 17 mod 5=217 \bmod 5 = 2, because 17=3×5+217 = 3 \times 5 + 2. Programmers call it clock maths: the numbers wrap back to 0 once they reach mm.

The division identity

a=q⋅m+r,0≤r<m,a mod m=ra = q \cdot m + r, \qquad 0 \le r < m, \qquad a \bmod m = r
q=⌊a/m⌋q = \lfloor a / m \rfloor is the quotient (Python a // m) and rr is the remainder (Python a % m). So 25=2⋅12+125 = 2 \cdot 12 + 1 gives 25 mod 12=125 \bmod 12 = 1.
  • Dividend aa

    The number you start with, such as 25 hours or index 7.

  • Modulus mm

    The size of the cycle: 12 hours, 5 array slots, 10 buckets.

  • Quotient qq

    How many full laps fit. Full laps change nothing about where you end up.

  • Remainder rr

    Where you land: always one of 0,1,…,m−10, 1, \dots, m - 1. 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. 1

    Divide

    25÷12=225 \div 12 = 2 remainder 1. The quotient is 2.

  2. 2

    Remove full cycles

    2×12=242 \times 12 = 24 steps are two complete rotations, which bring the hand back to 0.

  3. 3

    Keep the leftover

    25−24=125 - 24 = 1. The hand lands on 1, and that is the answer.

Computing a mod m by laps

Subtracting laps one at a time is the idea; 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: 25≡1(mod12)25 \equiv 1 \pmod{12}, read "25 is congruent to 1 mod 12". Equivalently, their difference is a multiple of mm.

Definition of congruence

a≡b(modm)  ⟺  m∣(a−b)  ⟺  a mod m=b mod ma \equiv b \pmod m \iff m \mid (a - b) \iff a \bmod m = b \bmod m
m∣(a−b)m \mid (a - b) means mm divides a−ba - b exactly. 25−1=24=2⋅1225 - 1 = 24 = 2 \cdot 12, so 25≡1(mod12)25 \equiv 1 \pmod{12}; also 13≡113 \equiv 1 and −11≡1-11 \equiv 1.
CongruenceWhyWhere you meet it
25≡1(mod12)25 \equiv 1 \pmod{12}25−1=24=2⋅1225 - 1 = 24 = 2 \cdot 12Hour 25 is 1 o'clock
7≡2(mod5)7 \equiv 2 \pmod 57−2=57 - 2 = 5Index 7 of a 5-slot ring is slot 2
42≡2(mod10)42 \equiv 2 \pmod{10}42−2=4042 - 2 = 40Key 42 in 10 buckets goes to bucket 2
n≡0(mod2)n \equiv 0 \pmod 222 divides nnn % 2 == 0 is the even test
−3≡2(mod5)-3 \equiv 2 \pmod 5−3−2=−5-3 - 2 = -5Why 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

(a+b) mod m=((a mod m)+(b mod m)) mod m(a⋅b) mod m=((a mod m)⋅(b mod m)) mod m\begin{gathered} (a + b) \bmod m = \big((a \bmod m) + (b \bmod m)\big) \bmod m \\[4pt] (a \cdot b) \bmod m = \big((a \bmod m) \cdot (b \bmod m)\big) \bmod m \end{gathered}
You may reduce the inputs before adding or multiplying and still get the same remainder. (9+5) mod 12=2(9 + 5) \bmod 12 = 2 either way; (17⋅23) mod 5=(2⋅3) mod 5=1(17 \cdot 23) \bmod 5 = (2 \cdot 3) \bmod 5 = 1.

Subtraction: add m back

(a−b) mod m=((a mod m)−(b mod m)+m) mod m(a - b) \bmod m = \big((a \bmod m) - (b \bmod m) + m\big) \bmod m
The +m+ m keeps the middle value non-negative, so the formula gives the same answer in every language.
OperationReduce as you go?How
AdditionYes(a + b) % m
SubtractionYes, add mm back(a - b + m) % m
MultiplicationYes(a * b) % m, each factor already below mm
Power aea^eYes, by squaringpow(a, e, m), O(log e)
Division a/ba / bNoMultiply by the inverse: bm−2 mod mb^{m-2} \bmod m when mm 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.

ExpressionPythonC / C++ / Java / JavaScriptRule
-3 % 52-3floor vs truncate
3 % -5-23sign of divisor vs dividend
-10 % 32-1−10=−4⋅3+2-10 = -4 \cdot 3 + 2 vs −3⋅3−1-3 \cdot 3 - 1
((-3 % 5) + 5) % 522safe everywhere
In Python, math.fmod(-3, 5) gives the C-style -3.0 if you ever need it.

Getting a safe remainder in any language

Or skip the check and always write ((n % m) + m) % m.
Python
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 0
Python's % already returns a value in 0..m-1 for a positive modulus.
Edit and run it in your browser

Wrap-around

Circular arrays and ring buffers

A circular array treats the end as joined to the start, so index ii means slot i mod ni \bmod n. Index 7 in an array of size 5 is slot 7 mod 5=27 \bmod 5 = 2. 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

The write position is (head + count) % size. Once full, each push overwrites the oldest item and moves the head on.
Python
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]
A fixed-size ring buffer that keeps the latest items, the core of audio buffers and log rotation.
Edit and run it in your browser
  • 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 ii moves to (i+k) mod n(i + k) \bmod n when rotating right by kk.

Hashing

Hash tables: the bucket assignment

Hash functions return huge numbers, but a table only has mm buckets numbered 0 to m−1m - 1. The last step is always bucket=hash(key) mod m\text{bucket} = \text{hash}(key) \bmod m. Key 42 in 10 buckets lands in bucket 2. Java's "hello".hashCode() is 99162322, and 99162322 mod 16=299162322 \bmod 16 = 2.

From key to bucket
  1. 1Key42 or "hello"
  2. 2Hasha large integer
  3. 3mod msqueezes it into 0..m-1
  4. 4Bucketstore or look up here

Lookups repeat the same calculation and jump straight to the bucket: O(1) on average.

Keysmod 10mod 7 (prime)
10, 20, 30, 40, 500, 0, 0, 0, 0: one long chain3, 6, 2, 5, 1: spread out
42, 17, 52, 99, 72, 7, 2, 9, 7: two collisions0, 3, 3, 1, 0
Keys that share a factor with mm crowd into a few buckets. A prime mm shares no factor with most patterns.

Big numbers

Overflow and the 10⁹ + 7 trick

Counting problems produce enormous answers: 100!100! 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

(109+6)2≈1.0×1018  <  263−1≈9.2×1018(10^9 + 6)^2 \approx 1.0 \times 10^{18} \; < \; 2^{63} - 1 \approx 9.2 \times 10^{18}
Both factors are below 109+710^9 + 7 after reducing, so their product fits in a signed 64-bit integer, and the sum of two reduced values, about 2×1092 \times 10^9, even fits in a signed 32-bit one.

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 bp−2 mod pb^{p-2} \bmod p.

  • Safe

    Products of two reduced values fit in 64 bits; sums fit in 32 bits.

Python
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) # 1
Reduce inside the loop. Python ints never overflow, but reducing keeps them small and fast.
Edit and run it in your browser

Fast power

Modular exponentiation

To compute be mod mb^e \bmod m for a huge ee, do not multiply ee 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 35 mod 73^5 \bmod 7: 5=10125 = 101_2, so 35=34⋅313^5 = 3^4 \cdot 3^1.

Square and multiply

be={(b2)e/2e evenb⋅(b2)(e−1)/2e odd⇒O(log⁡e) multiplicationsb^{e} = \begin{cases} \left(b^{2}\right)^{e/2} & e \text{ even} \\[2pt] b \cdot \left(b^{2}\right)^{(e-1)/2} & e \text{ odd} \end{cases} \qquad \Rightarrow \qquad O(\log e) \text{ multiplications}
Each round halves the exponent. 35 mod 73^5 \bmod 7: result becomes 3, the base squares to 2 then 4, and 3⋅4 mod 7=53 \cdot 4 \bmod 7 = 5. For e=1018e = 10^{18}, about 60 rounds.

The fast power loop

This is how RSA and Diffie-Hellman raise numbers to exponents hundreds of digits long.
Python
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, instantly
Python's three-argument pow does the same thing in C.
Edit and run it in your browser

Pattern spotting

When to reach for mod

Does this problem want mod?

Wrap, hash, shrink, test: four reasons to write %.
PatternMeaning
n % 2 == 0 / n % 2 == 1Even or odd check
i % len(arr)Circular indexing
(head + i) % sizeRing buffer access
hash(key) % bucketsHash table index
(a + b) % m, (a * b) % mModular addition and multiplication
((n % m) + m) % mSafe negative mod in any language
result % (10**9 + 7)Keep huge answers small
n % 10, n //= 10Peel off decimal digits
The plain % is O(1) on modern CPUs; modular exponentiation is O(log e).

Safe habits

  • Reduce after every +, - and * when a modulus is given.
  • Add m back before taking mod of a difference.
  • Use pow(b, e, m) or square-and-multiply for powers.
  • Write MOD = 10**9 + 7 as an integer constant.

Common slips

  • Taking mod only at the very end, after values have overflowed.
  • Trusting -3 % 5 to 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

  • a mod ma \bmod m is the remainder rr in a=q⋅m+ra = q \cdot m + r, always between 0 and m−1m - 1.
  • Think of a clock: full laps vanish, only the leftover steps count. 25 mod 12=125 \bmod 12 = 1.
  • a≡b(modm)a \equiv b \pmod m means aa and bb leave the same remainder; mm divides a−ba - b.
  • Reduce at every step for addition, subtraction (add mm back) and multiplication; division needs an inverse.
  • Python's -3 % 5 is 2; C, Java and JavaScript give -3. Portable fix: ((n % m) + m) % m.
  • arr[i % n] wraps indexes; hash(key) % m picks a bucket; (i + 1) % n moves a ring pointer.
  • 109+710^9 + 7 is prime and small enough that products of reduced values fit in 64 bits.
  • Fast power computes be mod mb^e \bmod m in O(log e) multiplications.

Sources