Congruences and Fermat's Little Theorem: Computing in a World of Remainders
Prerequisite:Primes and the Prime Number Theorem: From Infinitude and Unique Factorization to the Law of Distribution
0. Key points
Section titled “0. Key points”- Sorting the integers by “the remainder on division by ” carries addition, subtraction, and multiplication along unchanged. This is the congruence , and the quotient set becomes a commutative ring.
- Division, by contrast, is not always available. The class has an inverse in exactly when , and the sole reason for this is Bézout’s identity.
- When is a prime , the ring is a field: every nonzero element is invertible. Fermat’s little theorem (for ) follows from this.
- The extension to general is Euler’s theorem , whose proof has exactly the same skeleton as Fermat’s: multiplication by is a permutation of the group of units.
- The Chinese remainder theorem is the isomorphism (for ), and it supports both the multiplicativity of and the correctness of RSA.
- The converse of Fermat’s little theorem is false. Carmichael numbers such as are counterexamples, and it is they that pushed primality testing towards probabilistic algorithms.
1. Motivation — arithmetic on a clock face
Section titled “1. Motivation — arithmetic on a clock face”Suppose it is o’clock; what time will it be hours from now? We compute , but there is no on a clock face, so we answer o’clock. In everyday life we are already adding inside the world of “remainders on division by “.
This way of computing with remainders alone had been used piecemeal for a long time. Casting out nines, which detects multiples of from the sum of the digits, was a medieval merchant’s device for checking arithmetic, and calendar computations are in essence computations with remainders. But it was Gauss, in the Disquisitiones Arithmeticae (1801), who systematized the practice with the symbol and treated it as an algebraic system in its own right. With this single piece of notation Gauss unified techniques of number theory that had until then been scattered.
Why should merely introducing a symbol produce progress? Because congruences obey almost the same rules as equalities. “One may add the same thing to both sides” and “one may multiply both sides by the same thing” both hold, so our instincts for manipulating equations carry over intact. As a result a problem such as finding the last two digits of — a computation with a -digit number if carried out honestly — turns into a handful of multiplications of numbers below .
There is, however, one decisive difference from equality: division is not free. We have while . Pinning down exactly where the boundary between “divisible” and “not divisible” lies is the technical heart of this article, and from it flow both Fermat’s little theorem and RSA.
This article is the sequel to The charm of primes — the prime number theorem. Think of it as looking at primes from the side of “how they behave” rather than “how many there are”.
2. Preliminaries — the division algorithm and Bézout’s identity
Section titled “2. Preliminaries — the division algorithm and Bézout’s identity”Throughout, denotes the integers and (excluding ). We write for ” divides ”, that is, for the existence of some with .
Theorem 2.1(Division algorithm)
Let and . Then there is exactly one pair of integers with
Proof(Theorem 2.1)
We first prove existence. Consider the set . Taking to be a sufficiently small negative integer (for instance ) gives , so . Being a nonempty set of nonnegative integers, has a least element by well-ordering(Axiom 3.1)[Techniques of Proof].
If , then is again nonnegative and lies in , while , contradicting the minimality of . Hence .
Now uniqueness. Suppose with . Then . The right-hand side satisfies , so , hence , that is, . Substituting back gives .
We write this as . This is the meaning of when it is used as “the operation of taking the remainder” (the that appears later is a parenthetical indicating a relation, and plays a different role).
When and are not both , we write for the largest common divisor of and . When we say that and are coprime (the notation agrees with Definition 2.1[Primes and the Prime Number Theorem]).
Theorem 2.2(Bézout's identity)
Let be integers, not both . Then there exist integers with
Moreover, coincides with the set of all multiples of .
Proof(Theorem 2.2)
Put and let be the set of positive integers in . If then lies in ; if then , so . Either way , so by well-ordering it has a least element .
We first show . By Theorem 2.1 write with ; then
If then and , contradicting the minimality of . Hence , that is, . The same argument gives , so is a common divisor of and .
Conversely, let be any common divisor of and . Both terms on the right of are divisible by , so and therefore . Hence , and is the representation sought.
The last assertion follows because every element of is a multiple of (since and ), while conversely every multiple of lies in .
Lemma 2.3(Euclid's lemma)
If and , then . In particular, if is prime and , then or .
Proof(Lemma 2.3)
By Theorem 2.2 there are integers with . Multiplying both sides by gives
By hypothesis , so the first term on the right is divisible by , and the second term is plainly a multiple of . Hence .
For the second statement, suppose . Since is prime, is either or , and is excluded, so . Applying the first part with , , yields .
3. Congruences
Section titled “3. Congruences”Definition 3.1(Congruence)
Let . For integers , if we say that and are congruent modulo and write
We call the modulus of the congruence.
Congruence modulo is an equivalence relation on , and it has exactly equivalence classes, namely the sets of integers congruent to each of .
Proof(Proposition 3.2)
Reflexivity holds because . Symmetry follows because if then is also a multiple of . For transitivity, if and then .
Now we count the classes. By Theorem 2.1 every can be written with , so , that is, . Hence each class contains one of . Moreover if then , so and is not congruent to . Therefore there are exactly classes.
For equivalence relations in general, see Relations and equivalence relations — what does “the same” mean? (the first half of the proposition above is Proposition 3.4[関係と同値関係]). We write or for the class containing and call it the residue class of .
Proposition 3.3(Arithmetic of congruences)
Suppose and . Then
In particular for every .
Proof(Proposition 3.3)
By hypothesis there are integers with and . For addition,
is divisible by . Subtraction is identical up to a change of sign. For multiplication,
so . Here we used the device of adding and subtracting .
The statement about powers is proved by induction on . The case is the hypothesis itself. If , applying the multiplicative statement to this and to gives .
It is Proposition 3.3 that licenses us to treat congruences like equations. Thanks to it, enormous powers can be tracked using remainders alone.
Example 3.4(The last two digits of 2 to the 100th power)
We compute . We have . Squaring both sides using Proposition 3.3,
Furthermore , so and . Therefore
The number has digits, yet we found its last two digits to be without ever multiplying numbers of more than three digits.
Example 3.5(Casting out nines and the test for 11)
Since , Proposition 3.3 gives . Hence for (where the are the digits),
This proves that multiples of can be detected from the digit sum. For example, if then , so .
On the other hand , so and
For , attaching alternating signs starting from the units digit gives .
Division alone is a different matter. The next proposition is the precise rule for “dividing both sides” of a congruence.
Proposition 3.6(Cancellation law)
Let , , and . Then
In particular, one may conclude from precisely when .
Proof(Proposition 3.6)
Write and ; then (if were a common divisor of the two, then would be a common divisor of and , contradicting the maximality of ).
The congruence says , that is, ; dividing both sides by gives . Since , Lemma 2.3 yields , that is, .
If then , so .
Example 3.7(An example where division breaks down)
We have and , and , so . But is not a multiple of , so . As Proposition 3.6 says, here , so the most one may correctly conclude is — and indeed satisfies this.
4. The ring Z/nZ and its group of units
Section titled “4. The ring Z/nZ and its group of units”Definition 4.1(Ring of residue classes)
Let . We write
for the set of all residue classes modulo , with operations defined by
There is something to be verified in this definition. The symbol denotes an equivalence class, and there is freedom in the choice of the representative . Unless and whenever and , the operations are not well defined. But this is precisely the content of Proposition 3.3. Hence the operations are independent of the choice of representatives (the same statement phrased in the language of quotient sets is Theorem 5.4[関係と同値関係]).
With the operations of Definition 4.1, the set is a commutative ring with identity .
Proof(Proposition 4.2)
Associativity, commutativity, and distributivity all follow at once from the corresponding laws in . For instance, distributivity reads
where only the third equality uses distributivity in ; the others merely rewrite the definition. The additive identity is , the additive inverse of is , and the multiplicative identity is .
For ring theory in general see Foundations of rings and fields, and for the viewpoint of as the quotient ring by the ideal see Theorem 4.2[イデアルと剰余環] in Ideals and quotient rings.
Definition 4.3(Group of units)
An element of the ring is called a unit if there is some with . The set of all units is written .
An element is a unit if and only if . Moreover is a group under multiplication.
Proof(Proposition 4.4)
If , then by Theorem 2.2 there are integers with . This says , that is, , so .
If , then for some integer , so . Now divides both terms on the left, so and therefore .
Let us check the group axioms. The class is a unit. If and are units with and , then , so the product is a unit and the operation is closed. Associativity comes from multiplication in the ring, and the existence of inverses is the definition of a unit.
The ring is a field if and only if is prime.
Proof(Corollary 4.5)
Let be prime. Saying means , and since is prime, with excluded, so . By Proposition 4.4, is a unit, so is a field (and ensures ).
Conversely, if is composite then with , and , while . A field has no zero divisors (if and is invertible, multiplying both sides by gives ), so this is not a field. For we have , which violates the definition of a field.
For a prime we write for the field . What Corollary 4.5 says is that the primes are the only moduli producing a “finite world in which one can divide”. The special status of primes takes an algebraic form here. The same statement is obtained from the side of ring theory as Corollary 5.5[環と体の基礎].
Definition 4.6(Euler's totient function)
Example 4.7(The group of units of Z/12Z)
Among through , those coprime to are , four in all, so and . Writing out the multiplication table,
so every element other than the identity has order . This group is therefore isomorphic to the Klein four-group and is not cyclic. By contrast, it is known that for a prime the group is always cyclic (existence of a primitive root).
Theorem 4.8(Chinese remainder theorem)
Let with . Then the map
is a well-defined ring isomorphism. In particular, for any integers the simultaneous congruences and have a unique solution modulo .
Proof(Theorem 4.8)
Well-definedness: if then , hence in particular and , so . That is a ring homomorphism follows at once, since addition and multiplication in each component are exactly the operations of Definition 4.1; and is clear.
Injectivity: suppose , so and . Writing we get , and since , Lemma 2.3 gives , say . Hence , that is, . Since the kernel of the homomorphism is trivial, is injective.
Surjectivity: the domain and codomain are both finite, with and elements respectively, hence of equal size. An injective map between finite sets of equal cardinality is surjective, so is a bijection.
The final assertion is exactly the bijectivity of : the preimage of is a single residue class , which means existence of a solution together with uniqueness modulo .
If then . Moreover, if is the prime factorization of , then
Proof(Corollary 4.9)
A ring isomorphism carries units to units and non-units to non-units (since , and likewise in the other direction for ). Hence the map of Theorem 4.8 induces a bijection between groups of units,
Counting elements on both sides gives .
For a prime power , the integers from to that are not coprime to are the multiples of , namely , of which there are . Hence
Distinct prime powers are coprime, so repeated use of multiplicativity gives the formula.
5. Fermat’s little theorem and Euler’s theorem
Section titled “5. Fermat’s little theorem and Euler’s theorem”Fermat stated this theorem in a letter to Frénicle in 1640, but omitted the proof, saying it would run too long. The first published proof is due to Euler (1736).
Theorem 5.1(Fermat's little theorem)
Let be prime and let be an integer with . Then
Proof(Theorem 5.1)
Let and define a map by sending to . We argue in three steps.
Step one (the values of lie in ). From and , the second half of Lemma 2.3 gives . Hence , that is, .
Step two ( is injective). Suppose , so . From we get , so applying Proposition 3.6 with , , gives . Since and both lie between and , we have and hence . An injective map from the finite set to itself is a bijection, so is a permutation of .
Step three (comparing products). Since is a permutation,
On the other hand for each , so applying Proposition 3.3 times,
Combining the two gives . None of the with is divisible by , so repeated use of Lemma 2.3 gives , that is, . Hence Proposition 3.6 lets us cancel , and we obtain .
Let be prime. Then for every integer .
Proof(Corollary 5.2)
If , multiply both sides of Theorem 5.1 by to get . If , then , so Proposition 3.3 gives . In either case the congruence holds.
The form in Corollary 5.2 imposes no condition on , which makes it convenient; it will do the work later when we prove the correctness of RSA.
Theorem 5.3(Euler's theorem)
Let and with . Then
Proof(Theorem 5.3)
We lift the proof of Theorem 5.1 verbatim. Put , so that (Definition 4.6). Since , Proposition 4.4 gives .
Consider the map , . Because is a group (Proposition 4.4), we have , so really does map into . Moreover is an inverse map, so is a bijection, that is, a permutation of .
Now compute the product of all elements of in two ways. Reordering by a permutation does not change the product, so
Being a product of units, is itself a unit (by the group property in Proposition 4.4), so multiplying both sides by gives , that is, .
In the language of group theory, Theorem 5.3 is a one-liner: it is just the corollary of Lagrange’s theorem stating that for an element of a finite group , applied to . For details see Theorem 7.3[Subgroups and Cosets] in Subgroups and cosets (Lagrange’s theorem). The proof above amounts to writing out that special case without group-theoretic language. Historically it came first; the notion of a group was distilled from an accumulation of such concrete examples (Introduction to group theory — the definition and examples).
Let be prime and . Then the inverse of in is given by .
Proof(Proposition 5.5)
Since we have , so is an integer. By Theorem 5.1,
The inverse is unique (by general group theory, or because if and are both inverses then ), so this is .
Example 5.6(3 to the 1000th power modulo 7)
Since is prime and , Theorem 5.1 gives . As ,
Since , we get . Replacing the exponent by its remainder modulo is the practical use of the little theorem.
6. Applications — fast exponentiation, RSA, primality testing
Section titled “6. Applications — fast exponentiation, RSA, primality testing”6.1. Repeated squaring
Section titled “6.1. Repeated squaring”Computing does not require multiplications. Expand in binary and square repeatedly to get , multiplying in only the terms needed; then multiplications suffice. Since we reduce at every stage, no intermediate number ever exceeds (the justification is Proposition 3.3).
def power_mod(a, e, n): """Compute a^e mod n by repeated squaring. Requires e >= 0, n >= 1.""" result = 1 a %= n while e > 0: if e & 1: result = result * a % n a = a * a % n e >>= 1 return result
assert power_mod(2, 100, 100) == 76 # last two digits of 2^100assert power_mod(3, 1000, 7) == 4 # 3^1000 modulo 7To compute inverses we use the extended Euclidean algorithm, which is the proof of Theorem 2.2 turned into a procedure.
def ext_gcd(a, b): """Return (g, x, y) with g = gcd(a, b) and a*x + b*y = g.""" if b == 0: return (a, 1, 0) g, x, y = ext_gcd(b, a % b) return (g, y, x - (a // b) * y)
def inverse_mod(a, n): g, x, _ = ext_gcd(a % n, n) if g != 1: raise ValueError("the inverse does not exist") return x % n
assert inverse_mod(7, 120) == 1036.2. The RSA cryptosystem
Section titled “6.2. The RSA cryptosystem”Theorem 6.1(Correctness of RSA)
Let be primes, and set and . Suppose integers satisfy
Then for every integer ,
Proof(Theorem 6.1)
By hypothesis there is an integer with (we may assume ).
We first show . If then both sides are congruent to and the claim holds. If , then Theorem 5.1 gives , so
where we used the multiplicative and power statements of Proposition 3.3. Interchanging and , the same argument gives .
Hence and . Since are both prime, , so the injectivity argument of Theorem 4.8 (or Lemma 2.3 directly) gives , that is, .
It matters that we did not assume . Using Theorem 5.3 as it stands would require that hypothesis, but splitting into prime factors and using the form Corollary 5.2 dispenses with it.
flowchart TD A["choose primes p, q"] --> B["n = pq, phi = (p-1)(q-1)"] B --> C["choose e with gcd(e, phi) = 1"] C --> D["find d = e^-1 mod phi by extended Euclid"] D --> E["public key (n, e)"] D --> F["private key (n, d)"] E --> G["encrypt c = m^e mod n"] G --> H["decrypt m = c^d mod n"] F --> H
Example 6.2(Carrying RSA through with a small key)
Take and , so and . The exponent satisfies . Then solves , and from we get .
Encrypt the plaintext :
Since and , we get .
Now decrypt. Instead of computing directly, we use Theorem 4.8 and split into the moduli and .
Modulo : , and Theorem 5.1 gives ; since , we get .
Modulo : and ; since , we get . Here , so .
The unique solution modulo of and is . The plaintext has indeed been recovered.
6.3. The Fermat primality test and Carmichael numbers
Section titled “6.3. The Fermat primality test and Carmichael numbers”The contrapositive of Corollary 5.2 can be used to test primality: if for some (with ), then is not prime. This test runs quickly using repeated squaring.
The trouble is the converse. The fact that holds does not make prime.
Definition 6.3(Carmichael number)
A composite number satisfying for every integer with is called a Carmichael number.
Example 6.4(561 is a Carmichael number)
We have , which is composite. Also is divisible by each of (indeed ). If , then is divisible by none of , so Theorem 5.1 gives
Since is a multiple of each of these exponents, we get and similarly for the others, so modulo all three primes. Using Theorem 4.8 twice yields , that is, .
Here is the smallest Carmichael number. In 1994 Alford, Granville, and Pomerance proved that there are infinitely many Carmichael numbers.
The Fermat test is therefore not a deterministic primality test. The defect is remedied by the Miller–Rabin test, which writes with odd and inspects the sequence to detect the appearance of a nontrivial square root of . The principle is that if is a field (Corollary 4.5), the solutions of are only . A composite number slips past the Miller–Rabin test with probability at most for each base, so taking many bases gives certainty that is ample in practice.
The ring treated in this article is the first step in the practice of studying arithmetic objects by mapping them into finite algebraic systems. Pushing the same idea further leads to the procedure of counting, for each prime , the number of solutions of an equation over and assembling these counts into a generating function. Carrying this out for elliptic curves gives the Hasse–Weil -function, the subject of Elliptic curves and modular forms and Fermat’s Last Theorem. The names are similar, but this is the distance separating Fermat’s little theorem from his last theorem.
7. Exercises
Section titled “7. Exercises”Exercise 7.1Easy
Find the units digit of .
Solution
The units digit is the residue modulo . We have and (Corollary 4.9), so Theorem 5.3 gives . Since ,
Hence the units digit is .
Exercise 7.2Standard
Prove that for every prime (Wilson’s theorem).
Solution
For we have , so the claim holds; assume from now on that is an odd prime.
Since is a field (Corollary 4.5), all of are invertible. We first determine the elements that are their own inverses. The equation is equivalent to , and Lemma 2.3 gives or , that is, or . For an odd prime we have , so there are exactly two self-inverse elements, and .
The remaining elements split into pairs of distinct elements (uniqueness of inverses makes this pairing consistent). The product of each pair is , so
Hence .
Exercise 7.3Standard
For , show that (so that is a Fermat pseudoprime to the base ). Also compute and confirm that the base does detect as composite.
Solution
Base : from we get , and since , . Also and , so . Since , Theorem 4.8 gives , that is, .
Base : modulo we have and , so . Modulo , Theorem 5.1 gives , and since we get . Here and , so .
Since , we have , and the contrapositive of Corollary 5.2 shows that is composite. To find the value, solve and . Putting and using , , we need , that is, ; since , Proposition 3.6 gives . Taking gives , so .
Exercise 7.4Hard
Show that if a composite number is a Carmichael number (Definition 6.3), then is squarefree and for every prime factor of (the necessity half of Korselt’s criterion).
Solution
Let be a Carmichael number.
Squarefreeness. Suppose there were a prime with . From the prime factorization of we may write with and . Since , Theorem 4.8 supplies an integer with
This is not divisible by (because ) and is divisible by no prime factor of (because ), so .
By the binomial theorem, modulo ,
(every term of degree at least in is a multiple of ). Hence is equivalent to , that is, to . But , so — a contradiction. Therefore is squarefree.
The divisibility . Let be a prime factor of . The ring is a field and its group of units is cyclic of order . Take a generator , and use Theorem 4.8 to obtain with and ; then (since is squarefree we may use ).
By the definition of a Carmichael number, , and in particular . That is, holds in . The order of is , so the only with are the multiples of . Hence .
(For , that , , and all divide was checked in Example 6.4.)
References
Section titled “References”- Teiji Takagi, Shotō Seisūron Kōgi, 2nd ed., Kyoritsu Shuppan, 1971 (in Japanese) — Chapters 1 and 2. A classic, available in Japanese, running from the introduction of congruences through Euler’s theorem to primitive roots.
- G. H. Hardy and E. M. Wright, An Introduction to the Theory of Numbers, 6th ed., Oxford University Press, 2008 — Chapters 5 and 6 (congruences and Fermat’s theorem).
- K. Ireland and M. Rosen, A Classical Introduction to Modern Number Theory, 2nd ed., Springer GTM 84, 1990 — Chapters 3 and 4, treating the structure of residue rings and their unit groups algebraically.
- C. F. Gauss, Disquisitiones Arithmeticae, 1801 (English translation: Springer, 1986) — Sections 1 and 2 introduce the congruence symbol and its basic properties.
- R. L. Rivest, A. Shamir, L. Adleman, “A Method for Obtaining Digital Signatures and Public-Key Cryptosystems”, Communications of the ACM 21 (1978), 120–126. DOI: 10.1145/359340.359342
- W. R. Alford, A. Granville, C. Pomerance, “There are Infinitely Many Carmichael Numbers”, Annals of Mathematics 139 (1994), 703–722.
- Akihiko Yukie, Daisūgaku 1: Gunron Nyūmon, Nippon Hyoron Sha, 2010 (in Japanese) — Chapter 2, where the route from Lagrange’s theorem to Theorem 5.3 is set out.
Appendix: A combinatorial proof of Fermat’s little theorem
Section titled “Appendix: A combinatorial proof of Fermat’s little theorem”Setting up the objects to be counted. There is a proof of Theorem 5.1 that uses no residue classes at all. Let be an integer, a prime, and let be the set of all strings of beads in a row, each bead having one of colours. Then .
Separating monochromatic strings from the rest. Let the “cyclic shift” act on : the operation sending a string to . Since is the identity, is partitioned into the orbits of . If the orbit of some string has size , then is the least positive integer with fixing that string, and since also fixes it, . As is prime, either or .
An orbit has size 1 only for monochromatic strings. Saying means invariance under , that is, . There are as many such strings as there are colours, namely . The remaining strings all lie in orbits of size .
The conclusion of the count. The set obtained from by removing the monochromatic strings is a disjoint union of orbits of size , so its cardinality is a multiple of . That is,
which is nothing other than Corollary 5.2. When we have , so Proposition 3.6 lets us cancel and obtain . For negative or zero, replace by its remainder on division by ; Proposition 3.3 then gives the same conclusion.
What this proof means. The essential point is that it explains an arithmetic fact, “divisibility by ”, as a fact about counting: “the objects can be sorted into groups of ”. It is also the simplest manifestation of the general theory of orbits and fixed points, in which the group acts on a set and the size of each orbit divides the order of the group (Theorem 6.1[Subgroups and Cosets]).
Report an error in this article ・Operated by: Mugen Giken LLC ・Pricing ・Terms ・Legal notice
© 2026 夢現技研合同会社 ・Feeding the text to an LLM is welcome. Code samples are MIT licensed.