Intuition, Vocabulary and Foundations
Modular arithmetic keeps only the remainder after division by a positive modulus. A familiar analogy is a clock: starting at hour $10$ and moving forward $5$ hours gives hour $3$, because $15$ and $3$ occupy the same position on a $12$-hour clock.
For an integer modulus $m\ge 1$, integers $a$ and $b$ are congruent modulo $m$, written
$$ a\equiv b\pmod m, $$
when $m$ divides their difference:
$$ m\mid(a-b). $$
Thus $17\equiv5\pmod{12}$ because $12\mid(17-5)$. Congruence is an equivalence relation: it is reflexive, symmetric, and transitive. It partitions the integers into residue classes. Modulo $5$, every integer belongs to one of the five classes represented by $0,1,2,3,4$.
The canonical residue of $a$ modulo $m$ is the unique integer $r$ satisfying
$$ a\equiv r\pmod m \qquad\text{and}\qquad 0\le r\lt m. $$
Consequently, the canonical residue of $-17$ modulo $5$ is $3$, since $-17=5(-4)+3$. Programming languages do not all assign the same sign to a remainder, so portable code should normalize explicitly:
$$ \operatorname{norm}_m(a)=((a\bmod m)+m)\bmod m. $$
Congruence is preserved by addition and multiplication. These replacement rules permit intermediate values to be reduced without changing the final residue.
A modular inverse of $a$ modulo $m$ is a value $x$ satisfying
$$ ax\equiv1\pmod m. $$
It exists exactly when $\gcd(a,m)=1$. For example, $3^{-1}\equiv4\pmod{11}$ because $3\cdot4\equiv1\pmod{11}$. In contrast, $6$ has no inverse modulo $9$ because $\gcd(6,9)=3$.
Multiplication of residues forms a monoid: it is associative and has identity $1\bmod m$, but not every residue is invertible. The invertible residues form the group $(\mathbb Z/m\mathbb Z)^\times$. If $\gcd(a,m)=1$, Euler's theorem states $a^{\varphi(m)}\equiv1\pmod m$. For prime $p$ and $p\nmid a$, Fermat's little theorem gives $a^{p-1}\equiv1\pmod p$.
Modular arithmetic permits replacing any operand by a congruent residue before addition or multiplication. Division is the exception: replacing division by multiplication with an inverse is valid only when the divisor is coprime to the modulus.
| Concept | Example | Non-example or boundary | Assumption | Question answered |
|---|---|---|---|---|
| Congruence | $29\equiv5\pmod{12}$ | $29\not\equiv4\pmod{12}$ | $m\ge1$ | Do two integers represent the same residue class? |
| Canonical residue | $-17\bmod5=3$ after normalization | A language may report a negative remainder before normalization | Positive modulus | Which representative in $[0,m)$ should be stored? |
| Modular inverse | $3^{-1}\equiv4\pmod{11}$ | $6$ has no inverse modulo $9$ | $\gcd(a,m)=1$ | Can modular division by $a$ be performed? |
| Fermat reduction | $2^{100}\bmod7$ may reduce the exponent modulo $6$ | The coprimality rule does not justify reducing powers of a multiple of $7$ | Prime modulus and $p\nmid a$ | Which exponent cycle applies modulo a prime? |
| Euler reduction | $5^{100}\bmod12$ may reduce modulo $\varphi(12)=4$ | Euler reduction cannot be assumed for $6^{100}\bmod12$ | $\gcd(a,m)=1$ | Which general coprime exponent cycle applies? |
| Multiplicative monoid | Residues multiply associatively with identity $1\bmod m$ | A non-unit need not have an inverse | Closure, associativity, and identity | Why does binary exponentiation work without primality? |
| Modulus one | Every integer has canonical residue $0$ | There is no multiplicative inverse modulo $1$ | Handle $m=1$ explicitly | What happens in the one-element residue system? |
Step-by-Step Derivations and Algorithms
A direct computation of $a^e$ performs $e-1$ multiplications and creates an enormous intermediate integer. Binary exponentiation instead uses the binary expansion
$$ e=\sum_{i=0}^{k}b_i2^i, \qquad b_i\in\{0,1\}, $$
so that
$$ a^e=\prod_{i:b_i=1}a^{2^i}. $$
Successive squaring generates $a,a^2,a^4,a^8,\ldots$. At each iteration, the lowest exponent bit decides whether the current power contributes to the result.
For variables result, base, and remaining, the loop invariant is
$$ \text{result}\cdot\text{base}^{\text{remaining}} \equiv a^e\pmod m. $$
Initially result is the multiplicative identity and remaining is $e$. When remaining is odd, multiplying result by base accounts for its lowest binary bit. Squaring base and halving remaining preserves the invariant. At termination, the invariant yields the answer. The algorithm performs $O(\log e)$ modular multiplications with $O(1)$ auxiliary storage.
In a fixed-width integer type, evaluating $(ab)\bmod m$ may overflow before reduction. Double-and-add multiplication uses the binary expansion of $b$ to conditionally add successive doublings of $a$. This costs $O(\log b)$ modular additions. Wider intermediate types, Barrett reduction, and Montgomery multiplication can provide faster workload-specific alternatives.
The extended Euclidean algorithm constructs integers $x$ and $y$ satisfying
$$ ax+my=\gcd(a,m). $$
When the gcd is $1$, reduction modulo $m$ gives $ax\equiv1\pmod m$, so the normalized coefficient $x$ is the inverse of $a$. This works for prime and composite moduli alike.
Exponent reduction is optional. If $\gcd(a,m)=1$, Euler's theorem permits $a^e\equiv a^{e\bmod\varphi(m)}\pmod m$. For prime $p$, Fermat permits reduction modulo $p-1$ when $p\nmid a$. Without the relevant coprimality condition, blindly reducing the exponent can change the answer.
flowchart TD
A["Normalize operands and validate modulus"] --> B{"Requested operation"}
B -->|Power| C{"Exponent nonnegative?"}
B -->|Inverse or division| D["Compute extended gcd"]
B -->|Product| E{"Native product overflow-safe?"}
C -->|Yes| F["Binary exponentiation"]
C -->|No| D
D --> G{"gcd equals one?"}
G -->|Yes| H["Normalize Bezout coefficient"]
G -->|No| I["Report no inverse"]
H --> F
E -->|Yes| J["Multiply and reduce"]
E -->|No| K["Double-and-add or wide reduction"]
Binary exponentiation preserves $\text{result}\cdot\text{base}^{\text{remaining}}\equiv a^e\pmod m$ and runs in $O(\log e)$ modular multiplications with $O(1)$ extra space. Extended Euclid computes an inverse in $O(\log m)$ arithmetic steps, while double-and-add multiplication uses $O(\log m)$ additions after normalization.
Implementation, Complexity and Engineering
The public contract should require a positive modulus and return canonical residues. Modulus $1$ deserves explicit treatment: every nonnegative power and product is congruent to $0$, but no inverse exists. A negative exponent means inversion followed by ordinary exponentiation, so it must fail when the base is not a unit.
Python integers do not overflow, but the double-and-add implementation below models the technique required when a fixed-width product cannot hold $ab$. For high-throughput native code, a wider intermediate type or Montgomery reduction is usually faster.
| Implementation choice | Time and space | Numeric boundary | Failure mode | Mitigation |
|---|---|---|---|---|
| Repeated multiplication | $O(e)$ multiplications and $O(1)$ space | Intermediate powers grow rapidly without reduction | Unacceptable time for large exponents | Use binary exponentiation and reduce after every operation |
| Binary exponentiation | $O(\log e)$ multiplications and $O(1)$ space | Modular products may overflow fixed-width types | Correct recurrence with corrupted products | Pair it with a safe multiplication strategy |
| Native multiply then reduce | Usually constant time per product | Requires a type wide enough for $ab$ | Overflow before reduction | Use checked arithmetic or a wider intermediate type |
| Double-and-add multiplication | $O(\log m)$ additions and $O(1)$ space | Works with normalized nonnegative operands | Slower than hardware multiplication | Reserve it for platforms lacking safe wide products |
| Extended-Euclid inverse | $O(\log m)$ arithmetic steps | Requires $m\gt1$ and $\gcd(a,m)=1$ | Treating every nonzero residue as invertible | Check the gcd and report nonexistence |
| Fermat inverse $a^{p-2}$ | $O(\log p)$ multiplications | Requires known prime $p$ and $p\nmid a$ | Applying it to a composite modulus | Use extended Euclid unless primality is guaranteed |
| Exponent-cycle reduction | Reduction cost plus exponentiation | Requires the theorem's coprimality assumptions | Replacing an exponent by an invalid cycle residue | Check $\gcd(a,m)=1$ first |
| Montgomery reduction | Fast repeated products after setup | Best for odd moduli and many operations | Setup dominates small jobs | Use it for sustained large-number workloads |
Applications, Case Studies and Exercises
Modular arithmetic appears in cyclic schedules, checksums, rolling hashes, combinatorics, cryptography, pseudorandom generators, and algorithms whose exact counts are too large to store. The implementation strategy depends on the number of operations, the available product width, whether inverses are needed, and whether the modulus is known to be prime.
A useful testing oracle compares optimized operations with direct arbitrary-precision arithmetic on small random inputs. Important properties include normalization bounds, agreement with a trusted power function for nonnegative exponents, the identity $a\cdot a^{-1}\equiv1\pmod m$, and preservation of congruence under addition and multiplication.
Apply Modular Arithmetic & Fast Exponentiation
Case study 1 — cyclic scheduling. A reminder repeats every $17$ days. Starting at position $14$, determine the position after $10^6$ days.
- Normalize the displacement: $10^6\bmod17=9$.
- Add it to the starting position: $14+9=23$.
- Normalize again: $23\bmod17=6$.
- Verify that adding $17k$ days for any integer $k$ does not change the result.
Success criterion: the implementation returns a canonical residue in $[0,17)$ and produces the same answer for congruent displacements.
Case study 2 — modular division with a composite modulus. Solve
$$ 7x\equiv5\pmod{26}. $$
- Compute $\gcd(7,26)=1$, so an inverse exists.
- Extended Euclid gives $7\cdot15-26\cdot4=1$, hence $7^{-1}\equiv15\pmod{26}$.
- Multiply by $5$: $x\equiv75\equiv23\pmod{26}$.
- Verify that $7\cdot23\equiv5\pmod{26}$.
- Contrast this with $6x\equiv5\pmod{26}$: since $\gcd(6,26)=2$ does not divide $5$, no solution exists.
Success criterion: the toolkit returns $23$ for the first congruence and refuses to invent an inverse for $6$.
Hands-on exponentiation trace. Compute $3^{13}\bmod17$ by hand.
- Write $13=(1101)_2$.
- Track $3,3^2,3^4,3^8$ modulo $17$.
- Multiply only the powers corresponding to set bits.
- Confirm the result $12$ with
power_mod(3, 13, 17).
Tiered exercises
- Recall: Determine the canonical residues of $37$, $-37$, and $0$ modulo $8$.
- Classification: Decide which of $2$, $6$, $7$, and $9$ have inverses modulo $15$.
- Derivation: Prove that congruence is preserved under multiplication.
- Trace: Record every invariant value while computing $5^{23}\bmod19$.
- Implementation: Add a solver for $ax\equiv b\pmod m$, including cases with multiple solutions.
- Debugging: Explain why reducing every exponent modulo $m-1$ fails for arbitrary composite $m$.
- Testing: Generate random coprime pairs and verify $a\cdot\operatorname{inverse}(a,m)\equiv1\pmod m$.
- Extension: Replace double-and-add with a wider intermediate product and benchmark both approaches.
- Challenge: Implement Montgomery multiplication for odd moduli and identify when its setup becomes worthwhile.
Use normalization for every public result, binary exponentiation for large nonnegative powers, extended Euclid for general inverses, and overflow-safe multiplication when the native product is too narrow. Never assume a nonzero residue is invertible or that Euler or Fermat reduction applies without its hypotheses; these distinctions lead directly into linear congruences and the Chinese Remainder Theorem.
Next in the Series
In Linear Congruences & Chinese Remainder Theorem, we'll explore Solve one or many compatible modular constraints..