Contents / Discrete Mathematics / Number Theory
Chapter 6
Number Theory
The division algorithm with existence and uniqueness; primes, the square-root test and Euclid's infinitude; the Euclidean algorithm with its logarithmic bound and Fibonacci worst case; Bezout's identity from the extended algorithm; modular arithmetic, inverses and linear congruences; fast exponentiation by squaring; Fermat's little theorem, Euler's totient and the Chinese remainder theorem; and RSA with its correctness proved.
Introduction
Every other chapter of a discrete mathematics course teaches you to reason about finite structures. This one teaches you to compute inside one — the integers under addition and multiplication, cut down to a finite world by the single operation of taking remainders. That is a narrower subject than the number theory a mathematics department teaches, and deliberately so. The site's separate Number Theory subject develops divisibility, congruences and the classical theorems in their full generality, with the arithmetic of ideals waiting at the end of it. What follows is the working toolkit a computing student actually reaches for: how to decide whether a number is prime, how to compute a greatest common divisor quickly, how to invert and exponentiate modulo , how to reassemble a number from its remainders, and why those four skills are exactly what a public-key cryptosystem is built out of.
The word quickly is doing real work in that sentence, and it is the reason this material belongs in a computer science curriculum rather than being left to the mathematicians. Two problems about a -bit integer look superficially alike: find and find the prime factors of . The first is over in a few thousand machine operations. The second has resisted sixty years of concentrated effort and is believed to need more operations than there are atoms available to run them on. The gap between those two costs is not a footnote to the theory; it is the load-bearing wall under RSA, and the whole chapter is arranged to let you see where the gap comes from. Every algorithm here is stated with an operation count, and every operation count is proved.
The plan is linear. We start from division with remainder, which is the only primitive we assume, and from it derive the primes and the bound that makes small-scale primality testing feasible. Then we iterate division with remainder to get the Euclidean algorithm, prove that it is correct and that it runs in a number of steps proportional to the number of digits of its input — the Fibonacci numbers turn out to be its worst case, which is the prettiest complexity result in elementary mathematics. Running the same algorithm backwards produces Bézout coefficients, and Bézout coefficients produce modular inverses. Inverses plus fast exponentiation give us everything needed for the Chinese Remainder Theorem and then for RSA, whose decryption step we prove correct in the last section.
Throughout, is the set of integers and . We assume one property of without proof, the well-ordering principle: every nonempty set of non-negative integers contains a least element. Every existence proof below is ultimately an appeal to it.
6.1Division with Remainder and the Primes
Nothing in this chapter predates the operation you learned in primary school: divide, and keep the remainder. Stated precisely it is a theorem, not a definition, and the two clauses that make it useful — that the remainder exists, and that it is unique — both need an argument.
Theorem 6.1 (The division algorithm). Let and . Then there exist unique integers and with
We call the quotient and the remainder, and write .
Proof. Existence. Consider the set of non-negative numbers of that shape. It is nonempty: taking gives , since . By well-ordering has a least element for some . If we had then would be a smaller non-negative member of , contradicting minimality. Hence .
Uniqueness. Suppose with both remainders in . Subtracting, . The right-hand side satisfies , while the left-hand side is a multiple of ; the only multiple of of absolute value less than is . So , and then with forces .∎
Remark. The insistence that is what makes a function rather than a family of choices, and it is where hand computation and machine computation part company. In C, Java and Go the % operator takes the sign of the dividend, so -7 % 3 is , not the mathematical . Python's % agrees with this theorem. When a congruence in your code behaves strangely for negative inputs, this is almost always why; the repair is ((a % n) + n) % n.
Definition 6.2 (Divisibility). For integers and we say divides , written , if for some integer . Equivalently, when : exactly when .
Definition 6.3 (Prime and composite). An integer is prime if its only positive divisors are and . An integer that is not prime is composite, and then for some integers with .
The exclusion of is not squeamishness. If counted as prime, then would have infinitely many prime factorisations and the theorem that makes the primes worth naming would be false. A unit is not an atom.
Lemma 6.4 (Every integer above one has a prime divisor). Every integer has at least one prime divisor.
Proof. Let be the set of divisors of that are greater than . It is nonempty, since , so by well-ordering it has a least element . If were composite it would have a divisor with , and together with gives , so would be a member of smaller than . That is impossible, so is prime.∎
That lemma is the engine of two very different results: the bound, which makes primality testing cheap for small numbers, and Euclid's proof that the primes never run out.
Theorem 6.5 (The square-root bound). If is composite, then has a prime divisor with . Consequently, if no prime divides , then is prime.
Proof. Write with , which is possible because is composite. If both factors exceeded we would have , a contradiction; so . Since , the lemma Every integer above one has a prime divisor gives a prime , and . Transitivity of divisibility gives .
The second sentence is the contrapositive of the first, together with the observation that is either prime or composite.∎
Method 6.6 (Trial division). To test for primality: for each integer while , test whether . If some divides , report composite with witness . If the loop finishes, report prime.
Note the loop condition d*d <= n rather than d <= sqrt(n): it avoids a floating-point square root whose rounding could cut the search one step short. Testing every rather than every prime costs a constant factor and saves you from needing a list of primes before you can test for primality.
Proposition 6.7 (The cost of trial division). Trial division performs at most divisions. In terms of the input length — the number of bits actually written down — this is about divisions, which is exponential in .
Proof. The loop variable runs over , so there are fewer than iterations, each one division. Substituting gives .∎
Intuition. Halving an exponent sounds like progress, and for a -bit number it is: divisions is nothing. For a -bit RSA modulus it is divisions, which is not a large number of operations so much as a way of writing "never". The moral to carry forward is that a cost of is slow when is an input written in binary, while a cost of is fast. Every algorithm in the rest of the chapter is on the side of that line, and trial division is the only one that is not.
Example 6.8 (Certifying 211 prime). Show that is prime, and count the divisions performed.
Solution.
- Since and , the loop runs over : thirteen divisions at most.
- is odd, so . Its digit sum is , so . It does not end in or , so . Then , , , and the composite values of cannot divide if no prime below them does.
- The loop finishes with no witness, so by the theorem The square-root bound, is prime.
Example 6.9 (Factoring 8633 by trial division). Factor completely.
Solution.
- , so a prime factor at or below must exist if the number is composite.
- Testing in order, all fail until : .
- Both and are prime — neither has a prime factor at or below — so is the complete factorisation.
- Notice how hard the search worked: twenty-three divisions to split a four-digit number whose factors are nearly equal. Factoring is easy only when a small factor exists, and a cryptographer chooses and of equal size precisely to deny you that.
Theorem 6.10 (Fundamental Theorem of Arithmetic). Every integer can be written as a product of primes,
with and each , and this expression is unique.
Proof. Existence, by strong induction on . If is prime the factorisation is itself. Otherwise with ; both and are smaller than and greater than , so by the induction hypothesis each is a product of primes, and concatenating those two products expresses as a product of primes. Collecting equal primes into powers and sorting gives the stated form.
Uniqueness needs Euclid's lemma — if a prime divides a product it divides one of the factors — which in turn needs Bézout's identity, proved below as Bézout's identity. The argument is carried out in full in the chapter Divisibility and Primes, and we use the result here without repeating it.∎
Corollary 6.11 (Reading off exponents). Let and be positive integers written over a common list of primes as and , where an exponent of records an absent prime. Then if and only if for every .
Proof. If for all , then and the second factor is a positive integer, so . Conversely if , factor into primes; the factorisation of obtained by concatenating those of and must, by uniqueness, be the factorisation of , so every exponent in is at most the corresponding exponent in .∎
The primes are therefore a coordinate system: a positive integer is a vector of exponents, multiplication is vector addition, and divisibility is coordinatewise . The catch — the one that keeps cryptography in business — is that converting a number into those coordinates is the hard problem of the previous example.
Theorem 6.12 (Infinitude of the primes). There are infinitely many primes.
Proof. Suppose there were only finitely many, say , and set
Then , so by the lemma Every integer above one has a prime divisor it has a prime divisor , which must be some from the list. But divides the product , and it divides , hence it divides their difference . No prime divides , a contradiction. So no finite list contains every prime.∎
Pitfall. Euclid's argument does not claim that is prime. It claims that its prime factors are missing from the list. The distinction is easy to check: , which is composite, yet both and are indeed absent from , exactly as the proof predicts.
Method 6.13 (Sieve of Eratosthenes). To list every prime up to : create a boolean array indexed , all initially true. For each from while , if is still marked true, mark false every entry up to . The indices still true at the end are exactly the primes.
Proposition 6.14 (The sieve is correct). After the sieve terminates, index is marked true if and only if is prime.
Proof. No prime is ever marked false: the entries marked in the pass for are the multiples with , all of which are composite.
Conversely let be composite. By the theorem The square-root bound it has a prime divisor , so the pass for does occur, and is still true at that moment since no prime is ever marked false. Write ; from we get , so lies in the marked progression and is set false.∎
Starting each pass at rather than is worth noticing: every smaller multiple of has a prime factor below and was therefore already struck out. The total work is , which is about — essentially linear, and the reason a sieve is the right way to get all primes below a bound while trial division is the right way to test one number.
Example 6.15 (Sieving up to 30). Run the sieve to and count the primes found.
Solution.
- : strike .
- : still true, so strike (even multiples are already gone).
- : already false, skip. : strike . Then , so the loop ends.
- Survivors: — that is primes.
Remark. The prime counting function satisfies , the Prime Number Theorem. For a working programmer the useful reading is: a random odd integer near is prime with probability about , so generating an RSA prime means testing a few hundred candidates. The analytic machinery behind that estimate is developed in Analytic Number Theory; the estimate itself is all we need.
6.2Divisors, gcd and lcm
Divisibility rarely appears alone. What a computation usually needs is the largest thing two numbers have in common, or the smallest thing that contains both.
Proposition 6.16 (Linearity of divisibility). If and , then for all integers .
Proof. Write and . Then , and is an integer.∎
Small as it is, this proposition is used in almost every proof that follows; whenever an argument concludes "so divides the remainder too", this is why.
Definition 6.17 (Greatest common divisor). For integers not both zero, is the largest positive integer dividing both. If we call and coprime. By convention for .
Definition 6.18 (Least common multiple). For positive integers , is the smallest positive integer that both and divide.
The gcd is well defined because the common divisors of and all lie in when one of them is nonzero, so the set of them is finite and nonempty — it contains .
Theorem 6.19 (gcd and lcm from the factorisations). Let and over a common list of primes. Then
Proof. Let . By the corollary Reading off exponents, an integer divides exactly when for all , and divides exactly when . So is a common divisor precisely when for every , which says exactly that . Every common divisor divides , hence is at most , and is itself a common divisor; so is the greatest.
The lcm argument is the same with the inequalities reversed: and hold together precisely when for each , and the least such takes equality throughout.∎
Corollary 6.20 (Product of gcd and lcm). For positive integers and , .
Proof. For any two real numbers, . Multiplying the two formulas of the theorem gcd and lcm from the factorisations adds the exponents prime by prime, giving .∎
That corollary is how lcm is computed in practice: never by factoring, but as a / gcd(a,b) * b, dividing first so the intermediate value does not overflow.
Theorem 6.21 (Divisor-counting formula). If then the number of positive divisors of is
Proof. By the corollary Reading off exponents, the divisors of correspond exactly to the exponent tuples with , and distinct tuples give distinct integers by uniqueness of factorisation. There are choices for each coordinate, chosen independently, so the product rule gives tuples.∎
Example 6.22 (Divisors, gcd and lcm of 84 and 360). Compute , and .
Solution.
- Factor: and .
- .
- Minimum exponents: , so .
- Maximum exponents: , so .
- Check: , as the corollary Product of gcd and lcm requires.
Pitfall. This section's formulas are correct and almost useless for large inputs, because they all begin "factor ". A -bit gcd computed by factoring would take longer than the universe has existed; the same gcd by the algorithm of the next section takes under a millisecond. Keep the factorisation picture for understanding what the gcd is, and use Euclid to get it.
6.3The Euclidean Algorithm and its Cost
Euclid's algorithm is the oldest non-trivial algorithm still in daily use, and it is the first place where a student sees a proof of correctness and a proof of running time sitting side by side. Both are short. Both matter.
Lemma 6.23 (Euclid's identity). For integers and with ,
Proof. Write with , as the theorem The division algorithm permits. If divides both and , then by Linearity of divisibility it divides , so is a common divisor of and . Conversely if divides both and , the same proposition gives , so is a common divisor of and .
The two pairs therefore have identical sets of common divisors, and so the same greatest one.∎
Method 6.24 (Euclidean algorithm). Given , repeat until . Then output .
Theorem 6.25 (Correctness of the Euclidean algorithm). On input with and , the algorithm terminates and outputs .
Proof. Termination. The second component of the pair is a sequence of non-negative integers, and after the first step each is a remainder modulo its predecessor, hence strictly smaller: . A strictly decreasing sequence of non-negative integers is finite, so some component eventually equals and the loop stops.
Correctness. The quantity is an invariant of the loop body: the lemma Euclid's identity says precisely that replacing by leaves it unchanged. It holds on entry, so it holds on exit, where the pair is for some . Since , the returned value is the gcd of the original inputs.∎
Termination is one thing; speed is another. A decreasing sequence of integers could take steps to reach zero. It does not, and the reason is that a remainder is not merely smaller than the divisor — it is smaller by a lot, at least every other step.
Lemma 6.26 (Two steps at least halve). If , then .
Proof. Two cases. If then , since a remainder is always less than the divisor. If then the quotient is , because , and so .∎
Theorem 6.27 (The Euclidean algorithm runs in logarithmic time). On input with , the Euclidean algorithm performs at most division steps. In terms of the input length in bits, this is divisions.
Proof. Let , and be the sequence of values. The lemma Two steps at least halve applied to the pair gives . So along either the even-indexed or the odd-indexed subsequence, the values at least halve each time, and therefore
Since the values are non-negative integers, the sequence must reach once drops to or below, i.e. by . Each increment of covers two steps, giving at most divisions.
An integer with bits satisfies , so the bound is at most divisions.∎
Intuition. Compare the two costs honestly. Factoring a -bit number to get its gcd would take about operations; Euclid takes about divisions. The algorithm never learns a single prime factor of either input, and that is exactly why it is fast — it extracts the one piece of shared structure you asked for without solving the hard problem that also contains it. Almost every fast number-theoretic algorithm has this shape.
The bound is not tight, and the exact worst case is a small miracle: it is the input on which every quotient is as small as possible, namely , which forces the sequence of remainders to run backwards through the Fibonacci numbers.
Theorem 6.28 (Fibonacci inputs are the worst case). Let and . If the Euclidean algorithm on input with performs exactly division steps, then and . The pair attains this, taking exactly steps.
Proof. Induct on . For the algorithm stops after one division, which needs and so .
Suppose the claim holds for and let take steps. The first step produces the pair with , which takes steps, so by induction and . The first division gives with because , hence
For the attainment, run the algorithm on : since and for , every quotient is and the pair becomes . Repeating, the algorithm descends the Fibonacci sequence one index per step and halts on after exactly steps.∎
Corollary 6.29 (Lamé's bound). The number of division steps on input with is at most times the number of decimal digits of .
Proof. If the algorithm takes steps then by the theorem Fibonacci inputs are the worst case. Since where , taking base- logarithms gives , and . Hence , so where is the number of decimal digits of .∎
Example 6.31 (Counting the steps on a Fibonacci pair). How many division steps does the Euclidean algorithm take on , and what is the gcd?
Solution.
- and , so the theorem Fibonacci inputs are the worst case predicts steps where , that is .
- Running it: , , , , , , , , . That is nine divisions.
- The last nonzero remainder is , so — consecutive Fibonacci numbers are always coprime.
- For comparison, takes two steps despite the larger inputs. Size is not what makes the algorithm work hard; small quotients are.
Running the algorithm backwards: Bézout
Every division step wrote a remainder as a combination of the two numbers above it. Keeping those combinations as we go expresses the gcd itself in terms of the original inputs, which is the single most useful by-product in the chapter.
Theorem 6.32 (Bézout's identity). For any integers not both zero there exist integers with
Proof. We prove it by exhibiting the algorithm that produces and . Alongside the remainder sequence , , , maintain coefficient sequences
using the same quotients . We claim the invariant holds for every .
It holds at and by the initial values. Assuming it for and ,
By the theorem Correctness of the Euclidean algorithm the last nonzero remainder equals , and the invariant at reads .∎
Method 6.33 (Extended Euclidean algorithm). Keep a table with columns , , , . Seed the first two rows with and . At each step compute , then subtract times the current row from the row above it, componentwise, to produce the next row. Stop when reaches ; the previous row reads with .
Example 6.34 (A full extended Euclid trace). Compute and Bézout coefficients.
Solution.
- Set up the table and run it. Each row is (remainder, quotient used to make it, , ):
- Row three, for instance, comes from applied to all three columns: and .
- The last nonzero remainder is , so , with and .
- Check the invariant on the final row: .
Corollary 6.35 (The gcd is the least positive combination). is the smallest positive integer expressible as with . Consequently has an integer solution if and only if .
Proof. Let . By Bézout's identity, is expressible. By Linearity of divisibility, divides every combination , so every positive combination is at least ; hence is the least.
For the second claim. If then by the same linearity. Conversely if , multiply a Bézout expression by to get .∎
Example 6.36 (When can a linear Diophantine equation be solved?). Does have an integer solution? Does ?
Solution.
- . Since , the corollary The gcd is the least positive combination guarantees a solution to the first.
- Bézout for : . Multiplying through by gives , so works.
- For the second, , so no integer solution exists — every value of is a multiple of .
6.4Modular Arithmetic
Reducing modulo throws away everything about an integer except its remainder. What survives is still a system in which you can add, subtract and multiply, and it is finite — which is why a computer can work in it exactly, with no overflow and no rounding, for arbitrarily long computations.
Definition 6.37 (Congruence). For and integers , write if ; equivalently, if and leave the same remainder on division by .
Definition 6.38 (Residue classes). Congruence modulo is an equivalence relation, and its classes are the residue classes modulo . There are exactly of them, represented by ; the set of classes with its induced arithmetic is written .
Proposition 6.39 (Arithmetic respects congruence). If and , then
and hence for every .
Proof. Write and . Then and , both multiples of . For the product,
again a multiple of . The power statement follows by induction on , multiplying the congruence by .∎
This proposition is a licence to reduce early and often. It is what keeps intermediate values bounded by in a computation that would otherwise produce numbers with millions of digits.
Pitfall. Cancellation is the one rule that does not carry over. From you may not conclude . Modulo , (both are ), yet . The precise condition under which cancelling is legal is , and the next theorem says why.
Definition 6.41 (Modular inverse). An integer is an inverse of modulo if . We then write .
Theorem 6.42 (Inverses exist exactly for coprime residues). Let and . Then has an inverse modulo if and only if , and in that case the inverse is unique modulo .
Proof. () Suppose . By Bézout's identity there are integers with . Reading this modulo kills the term , leaving .
() Suppose , so for some , that is . Any common divisor of and divides the left side by Linearity of divisibility, hence divides ; so .
Uniqueness. If and , multiply the first congruence by to get , and the second by to get . The left sides are equal, so .∎
The proof is an algorithm. To invert modulo , run extended Euclid on , check the gcd is , and reduce the coefficient into . The cost is the cost of Euclid — logarithmic — which is why inversion is a cheap operation even for cryptographic-size moduli.
Example 6.43 (Inverting 17 modulo 43). Find .
Solution.
- Extended Euclid on : , , , . So and an inverse exists.
- Back-substitute: .
- Hence , so .
- Check: .
Corollary 6.44 (Cancellation modulo n). If and , then .
Proof. By the theorem Inverses exist exactly for coprime residues, exists modulo . Multiply both sides of by it and use Arithmetic respects congruence: .∎
Theorem 6.45 (Solving a linear congruence). Let . The congruence has a solution if and only if , and then it has exactly solutions modulo , forming one residue class modulo .
Proof. The congruence says for some integer , i.e. , which by the corollary The gcd is the least positive combination is solvable exactly when .
Suppose and write , , with . Dividing the equation through by gives the equivalent congruence , whose unique solution modulo is , the inverse existing by Inverses exist exactly for coprime residues. A single class modulo splits into exactly classes modulo , namely .∎
Example 6.46 (A congruence with three solutions). Solve .
Solution.
- and , so solutions exist — three of them modulo .
- Divide through by : . Since , we get .
- Lifting to modulus : .
- Check : .
Fast modular exponentiation
Computing by multiplying by itself times is hopeless when has hundreds of digits — and in RSA it always does. The fix is to exploit the binary expansion of the exponent.
Method 6.47 (Square-and-multiply). Write in binary as with . Set and, reading the bits from the most significant down to the least, at each bit replace and then, if that bit is , replace .
Theorem 6.48 (Correctness and cost of square-and-multiply). Square-and-multiply outputs using at most modular multiplications: one squaring per bit of after the first, plus one extra multiplication for each -bit.
Proof. Correctness. Let be the number formed by the top bits of . We claim that after processing bit the variable satisfies , by downward induction on .
Before any bit is processed, , the empty prefix. Suppose before bit is processed. Appending a bit to a binary numeral doubles the value and adds the bit: . The step squares, giving , and then multiplies by exactly when , giving . Each congruence is legitimate by Arithmetic respects congruence, which also permits the reduction modulo at every step.
After the last bit, and .
Cost. The number of bits is . Each contributes one squaring, and the -bits contribute one multiplication each; there are at most of those. The leading squaring acts on and can be skipped, leaving at most multiplications, all of operands smaller than .∎
Intuition. Repeated squaring gets you — exponents that double — so after squarings you have reached . The binary digits of tell you which of those doubling milestones to keep and multiply together. This is the same doubling trick as binary search or fast integer multiplication by shifts, and it is the reason a -bit RSA exponentiation costs a few thousand multiplications instead of of them.
Example 6.50 (Computing by hand). Evaluate with square-and-multiply, and count the multiplications.
Solution.
- , so the bits from the top are .
- Start . Bit : square to , multiply by , giving ().
- Bit : , then ().
- Bit : ().
- Bit : , then ().
- So , using three squarings and three multiplications after the trivial first step — six operations in place of twelve, on numbers never exceeding .
Remark. Hash tables are the other everyday use of this section. A division hash sends a key to ; the theory says the result is uniform only if the keys are, and that a modulus sharing a factor with structure in the keys (say when keys are pointers, always multiples of ) collapses the table into a fraction of its buckets. Choosing to be a prime not close to a power of two is the standard defence, and it is the theorem Inverses exist exactly for coprime residues in disguise: multiplying by a unit modulo a prime permutes the residues, so no bucket is privileged.
Fermat's little theorem
Definition 6.51 (Euler's totient). is the number of integers in that are coprime to . Equivalently, by the theorem Inverses exist exactly for coprime residues, it counts the invertible residues modulo .
Theorem 6.52 (Fermat's little theorem). Let be prime and let be an integer with . Then
Proof. Consider the numbers reduced modulo . None is , since and for . They are pairwise incongruent: if then, since , the corollary Cancellation modulo n gives , and both lie in , so .
So these residues are distinct and nonzero, hence are exactly in some order. Multiplying them together,
Since is prime, is coprime to and may be cancelled, leaving .∎
Remark. This is the special case of Euler's theorem, whenever , whose proof is the same argument run over the invertible residues instead of all nonzero ones. Both, with the group theory that explains them and the primality tests built on them, are treated at length in Classical Theorems; here we need only the two statements.
Example 6.53 (An exponent reduced by Fermat). Compute .
Solution.
- is prime and , so Fermat's little theorem gives .
- Write . Then .
- , so .
- The exponent dropped from to before any work was done — reducing the exponent modulo is always the first move.
6.5The Chinese Remainder Theorem
A number can be described by its remainders against several moduli instead of by its value. The Chinese Remainder Theorem says that when the moduli are pairwise coprime this description loses nothing, and that the translation back is a formula you can run.
Theorem 6.54 (Chinese Remainder Theorem). Let be pairwise coprime positive integers, , and let be any integers. Then the system
has a solution, and it is unique modulo . Explicitly, writing and letting be an inverse of modulo ,
Proof. The inverses exist. Fix . For each we have , and a number coprime to each of several factors is coprime to their product: any prime dividing and would divide some , contradicting coprimality. So and the theorem Inverses exist exactly for coprime residues supplies .
The formula solves the system. Fix and reduce modulo . For the factor contains , so that term vanishes. The surviving term is , by the defining property of . Hence for every .
Uniqueness. If and both solve the system then for every . The are pairwise coprime, so by the theorem gcd and lcm from the factorisations their lcm is their product , and a number divisible by each is divisible by that lcm. Hence , i.e. .∎
Corollary 6.55 (Splitting a modulus). If with , the map sending to the pair is a bijection from to that preserves sums and products. In particular .
Proof. The map is well defined, and it is onto by the existence half of the Chinese Remainder Theorem and one-to-one by its uniqueness half; both sides have elements. Sums and products are preserved because reduction modulo and modulo each respect arithmetic, by Arithmetic respects congruence.
For the totient: is invertible modulo exactly when , which happens exactly when and . So the bijection matches invertible elements with pairs of invertible elements, and counting gives .∎
Proposition 6.56 (Totient of a prime and of a semiprime). For a prime , . For distinct primes , .
Proof. Every one of is coprime to since has no divisors strictly between and , and itself is not; so . The second claim is the corollary Splitting a modulus applied to , , which are coprime because they are distinct primes.∎
Intuition. Think of two gears with and teeth. Coprimality means no tooth alignment repeats until both gears have completed a whole number of turns, so the combined pattern has full period and every pair of positions occurs exactly once. When the gears share a factor the combined period collapses, some pairs never occur — which is why , has no solution — and the theorem fails.
Example 6.57 (Reconstructing a number from three remainders). Find the smallest non-negative with , , , using the constructive formula.
Solution.
- , and , , .
- Inverses: and , so . , so . , so .
- Assemble: .
- Reduce: , so , and the smallest non-negative solution is .
- Check: , , .
Example 6.58 (Successive substitution instead of the formula). Solve and .
Solution.
- From the first congruence write and substitute into the second: , so .
- Invert modulo : , so . Then .
- So and , i.e. .
- Check: and . By hand, substitution is usually faster than the formula; the formula is what you implement, because it parallelises over .
Remark. CRT is not only an existence theorem, it is an optimisation. RSA private-key operations are routinely performed by reducing modulo and modulo separately, exponentiating on numbers half as long, and recombining with the formula above. Since multiplication cost grows faster than linearly in operand length, the two half-size exponentiations together cost roughly a quarter of the full one — a speedup of about four, for free.
6.6RSA: Putting the Toolkit to Work
Everything so far assembles into one system. RSA is worth the last section not because a first-year student will implement it, but because it is the only place where each tool's cost is visibly what makes the scheme possible or impossible: key generation needs primality testing, decryption needs modular inverses and fast exponentiation, and security needs factoring to be slow.
Method 6.59 (RSA key generation, encryption and decryption).
- Choose distinct large primes and set and .
- Choose with and ; compute with extended Euclid.
- Publish ; keep (and ) secret.
- Encrypt a message with as ; decrypt as , both by square-and-multiply.
Theorem 6.60 (Correctness of RSA decryption). Let be primes, , and let satisfy . Then for every integer with ,
Proof. Write for some integer , which is possible because .
We show , and the same argument with in place of gives .
If then both sides are and the congruence holds. Otherwise , so Fermat's little theorem applies and . Then
Now and both divide , and they are distinct primes, hence coprime; by the uniqueness half of the Chinese Remainder Theorem — or directly, since — we get divides , that is .
Finally both and lie in , so the congruence is an equality of representatives and decryption returns exactly the message sent.∎
Notice which case made the proof delicate. The naive argument — " by Euler, so " — needs and therefore says nothing about messages that happen to be divisible by or by . Splitting into the two prime moduli and handling separately is what upgrades the statement to every , which is what a correct decryption routine requires: a cryptosystem that fails on a one-in- set of messages is still broken.
Example 6.61 (A complete RSA round trip). Take , , . Find , then encrypt and decrypt the result.
Solution.
- and . Since , the exponent is legal.
- Extended Euclid on : , so , giving . So .
- Encrypt: . By square-and-multiply with : , then , (as ), then , . So .
- Decrypt: . Rather than grind, use the theorem Correctness of RSA decryption — , so .
- Check the theorem's hypothesis really is met: here, but the proof did not need it.
Example 6.62 (Breaking a small key). The public key is . Recover .
Solution.
- Factor by trial division: , and testing primes finds .
- Hence .
- Invert : extended Euclid on gives , so .
- The entire attack is three lines because has four digits. At bits step 1 is the wall — the security of the scheme is exactly the statement that factoring stays on the wrong side of the versus divide from the first section.
Pitfall. Textbook RSA as stated here is deterministic: the same message always encrypts to the same ciphertext, so an eavesdropper who suspects the plaintext can simply encrypt their guess and compare. Real deployments pad the message with randomness before exponentiating (OAEP). The mathematics of this section is correct and is not, by itself, a secure cryptosystem.
- Treating as prime. It is a unit, and admitting it would destroy uniqueness of factorisation.
- Believing Euclid's proof shows is prime. It shows only that its prime factors are new; .
- Stopping trial division at instead of , or writing
d <= sqrt(n)in floating point whered*d <= nis exact. - Confusing the statement with the number . The bar is a relation, not an operation.
- Calling the Euclidean algorithm fast because the numbers get small, then computing the gcd by factoring anyway. Factoring is the expensive step you were avoiding.
- Quoting the running time as arithmetic operations and then claiming bit operations. Each division on -bit numbers costs more than constant time.
- Sign errors in the extended algorithm. Always check the final row against before using it.
- Cancelling a common factor in a congruence without checking that it is coprime to the modulus.
- Asserting that always has a solution, or that it has only one when . It has solutions, or none.
- Reducing the exponent modulo rather than modulo (or ) in a modular power. Bases reduce mod ; exponents do not.
- Reporting a negative remainder from a language whose
%follows the dividend's sign, instead of normalising into . - Applying CRT to moduli that are not pairwise coprime, and being surprised by no solution or by solutions modulo the lcm rather than the product.
- Choosing RSA exponents with , which leaves non-invertible and the key pair unusable.
- Computing as for a composite . That formula is for primes; for it is .