Modular Arithmetic
Modular arithmetic keeps only the remainder after dividing by a modulus m. Addition, subtraction and multiplication can be reduced at every step, which keeps numbers small; division, ordering and exponents need extra care.
What Modular Arithmetic Is
Modular arithmetic is arithmetic on remainders. Fix a modulus m and replace every number by its remainder after dividing by m, a value from 0 to m − 1. A 12-hour clock is the everyday example: 9 o'clock plus 5 hours is 2 o'clock, because 14 leaves remainder 2 when divided by 12.
Two integers a and b are congruent when they leave the same remainder modulo m, or equivalently when m divides a − b; textbooks call this relation congruence modulo n, with n as the modulus. We write 38 ≡ 2 (mod 12). All numbers with the same remainder form one class, so there are exactly m classes, and every calculation can be done on their smallest members 0 … m − 1.
- a mod m: the remainder, 0 … m − 1
- a ≡ b (mod m) ⇔ m divides a − b
Modular Arithmetic Properties
- (a + b) mod m = ((a mod m) + (b mod m)) mod m
- (a − b) mod m = ((a mod m) − (b mod m) + m) mod m
- (a × b) mod m = ((a mod m) × (b mod m)) mod m
- (aᵏ) mod m: multiply k times, reducing after each product
The three properties below say you can reduce before or after an operation and get the same class. They hold because adding a multiple of m to a number does not change its remainder, and a multiple of m times anything is still a multiple of m.
- Reduce whenever you like for +, −, ×
- Not for ÷, comparisons or exponents
Why Programs Use 10⁹ + 7
Counting problems often have answers with hundreds of digits (the number of paths in a grid, n! for n = 10⁵), so they ask for the answer modulo 1,000,000,007. It is used because it is prime, so every non-zero value can be divided by (see below), and because it is just below 2³⁰: two residues add without overflowing a 32-bit int, and their product, below about 10¹⁸, fits in a signed 64-bit integer (limit about 9.2 × 10¹⁸). 998,244,353 is the other common choice; it suits the number-theoretic transform.
In the tracer, 20! = 2,432,902,008,176,640,000 is reduced step by step to 146,326,063, and 21!, which no 64-bit integer can hold, is one more step: 72,847,302.
- Prime: division works
- Below 2³⁰: products fit in 64 bits
Terms, operations, and practical uses
Congruence
- ModulusThe number m you divide by. Every value is replaced by its remainder 0 … m − 1.
- ResidueThe remainder a mod m; all integers with the same residue form one class.
- Congruenta ≡ b (mod m) when m divides a − b, e.g. 38 ≡ 2 (mod 12).
Operations
- Reduce as you goFor +, − and ×, taking the remainder before or after gives the same result.
- Normalise((x % m) + m) % m turns a negative remainder such as −4 into 8 (mod 12).
- Modular inverseb⁻¹ with b × b⁻¹ ≡ 1; exists only when gcd(b, m) = 1. Division is multiplication by it.
In code
- 10⁹ + 7A prime below 2³⁰: every non-zero value is invertible and products fit in 64 bits.
- OverflowProducts of residues reach m²; cast to 64 bits and reduce after every multiplication.
- Lost orderReduced values cannot be compared; 10⁹ + 8 becomes 1.
Code in Python, C++ and Java
MOD = 1_000_000_007
def mod_add(a, b, m=MOD):
return (a + b) % m
def mod_sub(a, b, m=MOD):
return ((a - b) % m + m) % m
def mod_mul(a, b, m=MOD):
return a * b % m
def factorial_mod(n, m=MOD):
result = 1 % m
for i in range(2, n + 1):
result = mod_mul(result, i, m)
return result
print("(17 + 20) mod 12 =", mod_add(17, 20, 12))
print("(3 - 7) mod 12 =", mod_sub(3, 7, 12))
print("17 * 20 mod 12 =", mod_mul(17, 20, 12))
print("(10^9 + 6)^2 mod (10^9 + 7) =", mod_mul(MOD - 1, MOD - 1))
print("20! mod (10^9 + 7) =", factorial_mod(20))
print("21! mod (10^9 + 7) =", factorial_mod(21))#include <iostream>
using namespace std;
const long long MOD = 1000000007;
long long modAdd(long long a, long long b, long long m = MOD) {
return (a + b) % m;
}
long long modSub(long long a, long long b, long long m = MOD) {
return ((a - b) % m + m) % m;
}
long long modMul(long long a, long long b, long long m = MOD) {
return a % m * (b % m) % m;
}
long long factorialMod(int n, long long m = MOD) {
long long result = 1 % m;
for (int i = 2; i <= n; i++) result = modMul(result, i, m);
return result;
}
int main() {
cout << "(17 + 20) mod 12 = " << modAdd(17, 20, 12) << "\n";
cout << "(3 - 7) mod 12 = " << modSub(3, 7, 12) << "\n";
cout << "17 * 20 mod 12 = " << modMul(17, 20, 12) << "\n";
cout << "(10^9 + 6)^2 mod (10^9 + 7) = " << modMul(MOD - 1, MOD - 1) << "\n";
cout << "20! mod (10^9 + 7) = " << factorialMod(20) << "\n";
cout << "21! mod (10^9 + 7) = " << factorialMod(21) << "\n";
}public class Main {
static final long MOD = 1_000_000_007L;
static long modAdd(long a, long b, long m) {
return (a + b) % m;
}
static long modSub(long a, long b, long m) {
return ((a - b) % m + m) % m;
}
static long modMul(long a, long b, long m) {
return a % m * (b % m) % m;
}
static long factorialMod(int n, long m) {
long result = 1 % m;
for (int i = 2; i <= n; i++) result = modMul(result, i, m);
return result;
}
public static void main(String[] args) {
System.out.println("(17 + 20) mod 12 = " + modAdd(17, 20, 12));
System.out.println("(3 - 7) mod 12 = " + modSub(3, 7, 12));
System.out.println("17 * 20 mod 12 = " + modMul(17, 20, 12));
System.out.println("(10^9 + 6)^2 mod (10^9 + 7) = " + modMul(MOD - 1, MOD - 1, MOD));
System.out.println("20! mod (10^9 + 7) = " + factorialMod(20, MOD));
System.out.println("21! mod (10^9 + 7) = " + factorialMod(21, MOD));
}
}Step through it
Running on m = 12, then m = 10⁹ + 7
Overflow and Negative Remainders in Code
Overflow happens before the % ever runs. With m = 10⁹ + 7, a * b % m on two 32-bit ints wraps around and gives garbage; cast to 64 bits first (1LL * a * b % m in C++, (long) a * b % m in Java). A product of three residues overflows even 64 bits, so reduce after every multiplication: (a * b % m) * c % m. Python's integers never overflow, but reducing still keeps them fast.
Negative results: in C, C++, Java, C# and JavaScript, the remainder takes the sign of the dividend, so (3 − 7) % 12 is −4, not 8. Python returns 8. Normalise with ((x % m) + m) % m, or add m before taking the remainder after a subtraction.
- Use 64-bit products; reduce after each one
- Normalise after subtraction
Division Needs an Inverse
(12 / 4) mod 7 = 3, but reducing first gives 5 / 4, which is not a whole number. Instead, find the number that undoes ×4: since 4 × 2 = 8 ≡ 1 (mod 7), dividing by 4 is the same as multiplying by 2, and 5 × 2 = 10 ≡ 3. That number is the modular inverse of 4.
An inverse of a exists exactly when gcd(a, m) = 1. Modulo 12, 4 has none: 4k mod 12 is only ever 0, 4 or 8. With a prime modulus every non-zero value has one. Finding inverses quickly (extended Euclid, or Fermat's little theorem for a prime) is covered in number theory basics; it is the key to nCr mod p in combinatorics.
- a / b ≡ a × b⁻¹ (mod m)
- b⁻¹ exists only when gcd(b, m) = 1
What the Mod Does Not Keep
Order. Congruence keeps equality, not size: 10⁹ + 8 reduces to 1 and looks smaller than 5. Take a max or min on exact values, never on reduced ones. Exponents. 2¹³ mod 12 = 8, but reducing the exponent 13 mod 12 gives 2¹ = 2. An exponent counts multiplications and is not a residue of m; it can only be shortened under specific conditions, such as Fermat's theorem for a prime m and gcd(a, m) = 1, and then modulo m − 1, not m.
Large powers are computed by repeated squaring with a reduction after every product (see number theory basics). Matrix exponentiation uses the same reductions on every cell of a matrix.
- Compare before reducing
- Never reduce an exponent mod m
Edge Cases and Bugs
m = 1: every value is 0, including 1, so a function returning 'pow(a, 0) = 1' must return 1 % m. m = 0 is undefined; reject it. Forgetting a reduction in one branch of a DP lets values grow until they overflow, often only on the largest test. Subtracting two reduced values can go negative even in Python-style code that later uses the value as an array index.
Keep helper functions (add, sub, mul) that always normalise, rather than writing % by hand in many places. Test with negative inputs, values just below m, m − 1 squared, and compare small cases against exact big-integer results.
- Handle m = 1; reject m ≤ 0
- One helper per operation