MATH2400 4,219 words·22 min read

Primality Tests

Generating Primes by Sieving#

A huge amount of what we have built so far leans on primes: unique factorisation, the fact that Zp\mathbb{Z}_p is a field, Fermat's Little Theorem, and the guarantee that Zp∗\mathbb{Z}_p^* has a primitive element. All of the applications in this topic (RSA, Diffie–Hellman, and friends in Cryptosystems) need us to actually get hold of primes. So there are two practical questions to answer: how do we generate a list of all the primes up to some bound, and how do we decide whether one particular number is prime?

The oldest answer to the first question is over two thousand years old and still the one we use.

Algorithm 6.1 (Sieve of Eratosthenes, or sieving). To generate a list of prime numbers less than or equal to a given number NN:

  • Start with a list LL of all integers from 22 up to NN.
  • The first entry p1p_1 in the list (namely 22) is prime. Mark every p1p_1th entry after p1p_1 in LL as composite.
  • The next entry in the list not marked as composite is prime. Label it pip_i, and mark every pip_ith entry after pip_i in LL as composite.
  • Repeat the previous step until the next non-composite entry pkp_k is greater than N\sqrt{N}. Then every non-composite entry remaining in the list is prime.

Basically, you walk along the list; the first number you have not already crossed out must be prime, and once you know it is prime you get to delete all of its multiples for free. Nothing in the algorithm ever divides anything — marking "every pip_ith entry" is just counting — which is exactly why sieving is so cheap compared to testing numbers one at a time.

Why does the first surviving entry have to be prime? Suppose kk is the first entry not yet marked as composite at some stage. Every prime smaller than kk has already had its turn, and each of those turns crossed out all of that prime's multiples; so kk is not a multiple of any prime less than kk, and hence has no factorisation at all other than 1×k1 \times k. That is precisely what it means for kk to be prime.

The other question is why we are allowed to stop so early, at N\sqrt{N} rather than NN.

Note

Fact
Every composite integer n>1n > 1 has a prime factor pp with p≤np \leq \sqrt{n}.

Proof. Since nn is composite we may write n=abn = ab with 1<a≤b<n1 < a \leq b < n. If we had a>na > \sqrt{n}, then b≥a>nb \geq a > \sqrt{n} as well, and so

n=ab>n×n=n,\begin{align*} n &= ab \\ &> \sqrt{n} \times \sqrt{n} \\ &= n, \end{align*}

which is absurd; hence a≤na \leq \sqrt{n}. Now a>1a > 1, so aa has some prime factor pp, and p≤a≤np \leq a \leq \sqrt{n} with p∣a∣np \mid a \mid n. ■\blacksquare

This one was Q7(a) of the Topic 1 tutorial, so it should look familiar. Its consequence for sieving is immediate: if a number m≤Nm \leq N survives every pass up to N\sqrt{N}, then mm has no prime factor $\leq \sqrt{N} $, and if mm were composite the Fact would hand us one. So mm is prime, and there is no work left to do. Stopping early is only legal because the crossing-out is exhaustive; if you skip a prime pass below N\sqrt{N}, composites survive.

It is worth noticing where each pass starts doing genuinely new work. In the pass for pp, the multiples 2p,3p,…,(p−1)p2p, 3p, \dots, (p-1)p have all already been crossed out, because each of 2,3,…,p−12, 3, \dots, p-1 has a prime factor smaller than pp whose pass has already run. So the first new entry killed in the pp pass is p2p^2, and once p2>Np^2 > N the pass achieves nothing at all — which is the N\sqrt{N} cutoff again, seen from the other side.

Sieving Out the Primes Below 50#

Example. Find all primes less than 5050 using the sieving technique.
We start with L=2,3,4,…,50L = 2, 3, 4, \dots, 50 and note that 50≈7.07\sqrt{50} \approx 7.07, so the passes will stop as soon as the next surviving entry exceeds 7.077.07.

Pass 1. The first entry is p1=2p_1 = 2, which is prime. Mark every second entry after it:

4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50.4,\ 6,\ 8,\ 10,\ 12,\ 14,\ 16,\ 18,\ 20,\ 22,\ 24,\ 26,\ 28,\ 30,\ 32,\ 34,\ 36,\ 38,\ 40,\ 42,\ 44,\ 46,\ 48,\ 50.

Pass 2. The next surviving entry is p2=3p_2 = 3, which is therefore prime. Mark every third entry after it, namely 6,9,12,…,486, 9, 12, \dots, 48; of these, the ones not already crossed out are

9, 15, 21, 27, 33, 39, 45.9,\ 15,\ 21,\ 27,\ 33,\ 39,\ 45.

Pass 3. The next surviving entry is p3=5p_3 = 5, so 55 is prime. Mark 10,15,20,…,5010, 15, 20, \dots, 50; the newly killed entries are

25, 35.25,\ 35.

Pass 4. The next surviving entry is p4=7p_4 = 7, so 77 is prime. Mark 14,21,28,35,42,4914, 21, 28, 35, 42, 49; the only new casualty is

49.49.

Stop. The next surviving entry is 1111, and 11>50≈7.0711 > \sqrt{50} \approx 7.07, so the algorithm halts and everything still standing is prime. Laying the list out in rows of ten, with a dot for every entry that has been crossed out (or was never in the list), the survivors are:

00 11 22 33 44 55 66 77 88 99
0+0+ ⋅\cdot ⋅\cdot 22 33 ⋅\cdot 55 ⋅\cdot 77 ⋅\cdot ⋅\cdot
10+10+ ⋅\cdot 1111 ⋅\cdot 1313 ⋅\cdot ⋅\cdot ⋅\cdot 1717 ⋅\cdot 1919
20+20+ ⋅\cdot ⋅\cdot ⋅\cdot 2323 ⋅\cdot ⋅\cdot ⋅\cdot ⋅\cdot ⋅\cdot 2929
30+30+ ⋅\cdot 3131 ⋅\cdot ⋅\cdot ⋅\cdot ⋅\cdot ⋅\cdot 3737 ⋅\cdot ⋅\cdot
40+40+ ⋅\cdot 4141 ⋅\cdot 4343 ⋅\cdot ⋅\cdot ⋅\cdot 4747 ⋅\cdot ⋅\cdot

Therefore, the primes less than 5050 are

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,2,\ 3,\ 5,\ 7,\ 11,\ 13,\ 17,\ 19,\ 23,\ 29,\ 31,\ 37,\ 41,\ 43,\ 47,

fifteen of them in total. Notice how little work the later passes did: pass 33 killed two numbers and pass 44 killed exactly one, consistent with the observation that the pp pass only starts biting at p2p^2 (2525 and 4949 respectively).

Testing One Number at a Time#

Sieving is the right tool when you want all the primes up to some bound, but it is wildly wasteful if you only care about one number; to decide whether 1018+910^{18} + 9 is prime you would rather not first write down every prime below 10910^9. Algorithms that decide whether or not a single number is prime are called primality tests.

Algorithm 6.2 (Basic primality test). To test whether a given positive integer nn is prime:

  • Start with a list LL of integers (or of primes, obtained via sieving) from 22 up to ⌊n⌋\lfloor \sqrt{n} \rfloor.
  • For each number aa in LL, find gcd⁡(a,n)\gcd(a,n), for instance via the Euclidean algorithm. If gcd⁡(a,n)≠1\gcd(a,n) \neq 1, we know nn is not prime and can terminate the algorithm.
  • If the list has been exhausted and the algorithm has not terminated, we know nn is prime and can terminate the algorithm.

This is just trial division dressed up, and it is correct for exactly the reason the sieve stops at N\sqrt{N}: if nn is composite it has a prime factor p≤np \leq \sqrt{n}, and that pp is somewhere in LL, where it will show up as gcd⁡(p,n)=p≠1\gcd(p, n) = p \neq 1. In some cases it is faster to run a divisibility test for aa than to grind through the Euclidean algorithm; if aa is one of 2,3,5,7,11,132, 3, 5, 7, 11, 13 you should just use the digit tricks.

Example. Use the basic primality test on n=97n = 97 and on n=91n = 91.
For n=97n = 97, we have 92=81≤97<100=1029^2 = 81 \leq 97 < 100 = 10^2, so ⌊97⌋=9\lfloor \sqrt{97} \rfloor = 9 and L=2,3,4,5,6,7,8,9L = 2,3,4,5,6,7,8,9. Running down the list,

gcd⁡(2,97)=1,gcd⁡(3,97)=1,gcd⁡(4,97)=1,gcd⁡(5,97)=1,gcd⁡(6,97)=1,gcd⁡(7,97)=1,gcd⁡(8,97)=1,gcd⁡(9,97)=1,\begin{align*} \gcd(2,97) &= 1, \quad \gcd(3,97) = 1, \quad \gcd(4,97) = 1, \quad \gcd(5,97) = 1, \\ \gcd(6,97) &= 1, \quad \gcd(7,97) = 1, \quad \gcd(8,97) = 1, \quad \gcd(9,97) = 1, \end{align*}

so the list is exhausted without a hit. Therefore, 9797 is prime.
For n=91n = 91, again ⌊91⌋=9\lfloor \sqrt{91} \rfloor = 9 since 81≤91<10081 \leq 91 < 100. The first six entries give gcd⁡(a,91)=1\gcd(a,91) = 1, but

gcd⁡(7,91)=7≠1,\begin{align*} \gcd(7,91) &= 7 \neq 1, \end{align*}

so we terminate immediately. Therefore, 9191 is not prime; indeed 91=7×1391 = 7 \times 13. Notice that the test hands you a factor as a by-product, which no other test in this note does.

So why look any further? Because ⌊n⌋\lfloor\sqrt{n}\rfloor is enormous for the nn we actually care about. A 20482048-bit RSA modulus has n≈21024\sqrt{n} \approx 2^{1024}, and no amount of computing power gets you through a list of that length. The obvious patch is to stop being exhaustive and sample aa at random instead, but that fails badly too. There are exactly n−ϕ(n)n - \phi(n) integers between 11 and nn that are not coprime with nn, and that count can be tiny compared with nn; so a randomly chosen aa almost never detects anything.

Example. For n=p2n = p^2 with pp prime, what is the chance that a randomly chosen integer between 11 and nn fails to be coprime with nn?
Recall from Fermats Little Theorem and Eulers Theorem that ϕ(p2)=p2−p\phi(p^2) = p^2 - p. So

p2−ϕ(p2)p2=p2−(p2−p)p2=pp2=1p.\begin{align*} \frac{p^2 - \phi(p^2)}{p^2} &= \frac{p^2 - (p^2 - p)}{p^2} \\ &= \frac{p}{p^2} \\ &= \frac{1}{p}. \end{align*}

Therefore, the chance of a random aa exposing n=p2n = p^2 as composite is only 1p\frac{1}{p}, and the chance of kk independent random choices all missing is (p−1p)k\left(\frac{p-1}{p}\right)^k. If pp has a hundred digits then 1p≈10−100\frac{1}{p} \approx 10^{-100} and you would need on the order of 1010010^{100} attempts before seeing anything; the randomised basic test is worthless. The problem is not that the basic test is wrong — it is perfectly correct — it is that its evidence is far too rare to stumble across by chance. What we want is a test whose evidence for compositeness is common, so that random sampling actually finds it.

Fermat's Little Theorem as a Primality Test#

Recall Fermat's Little Theorem: if pp is prime, then for all integers aa with p∤ap \nmid a,

ap−1≡1(modp).a^{p-1} \equiv 1 \pmod p.

Read forwards, this is a statement about primes. Read backwards — as its contrapositive — it becomes a statement about non-primes, and that is the version that does the work.

Note

Fact (contrapositive of Fermat's Little Theorem)
Given n∈Nn \in \mathbb{N}, if there is some a∈Za \in \mathbb{Z} with n∤an \nmid a and an−1≢1(modn)a^{n-1} \not\equiv 1 \pmod n, then nn is not prime.

Basically, every prime nn is obliged to satisfy an−1≡1a^{n-1} \equiv 1 for every aa it does not divide; so a single value of aa that breaks the rule is a cast-iron proof that nn is composite. An aa like this is called a witness to the compositeness of nn. The beauty of this is that computing an−1 mod na^{n-1} \bmod n by repeated squaring is fast even for astronomically large nn, and — unlike the basic test — witnesses turn out to be abundant rather than rare.

Algorithm 6.3 (Exhaustive Fermat primality test). To test whether a given positive integer nn is prime:

  • Start with a list LL of integers from 22 up to n−2n-2.
  • For each number aa in LL, find an−1 mod na^{n-1} \bmod n. If an−1 mod n≠1a^{n-1} \bmod n \neq 1, we know nn is not prime and can terminate the algorithm.
  • If the list has been exhausted and the algorithm has not terminated, we know nn is prime and can terminate the algorithm.

The list runs from 22 to n−2n-2 because the two endpoints it leaves out are useless: 1n−1=11^{n-1} = 1 always, and for odd nn we have (n−1)n−1=(−1)n−1=1(n-1)^{n-1} = (-1)^{n-1} = 1 in Zn\mathbb{Z}_n as well, since n−1n-1 is even. Neither can ever be a witness, so there is no point testing them.

It is worth checking that the exhaustive version really is a genuine primality test in both directions, and the key observation is that non-units can never pass.

Note

Lemma
If gcd⁡(a,n)=d>1\gcd(a,n) = d > 1, then an−1≠1a^{n-1} \neq 1 in Zn\mathbb{Z}_n.

Proof. Suppose instead an−1≡1(modn)a^{n-1} \equiv 1 \pmod n, so n∣an−1−1n \mid a^{n-1} - 1. Since d∣nd \mid n, transitivity gives d∣an−1−1d \mid a^{n-1} - 1. But d∣ad \mid a and n−1≥1n - 1 \geq 1, so d∣an−1d \mid a^{n-1} too; subtracting, dd divides

an−1−(an−1−1)=1,a^{n-1} - (a^{n-1} - 1) = 1,

so d=1d = 1, contradicting d>1d > 1. ■\blacksquare

So if nn is composite it has some divisor dd with 1<d<n1 < d < n, and taking a=da = d (which lies in the list, since 2≤d≤n/2≤n−22 \leq d \leq n/2 \leq n-2 for n≥4n \geq 4) gives a value that fails the test. Hence Algorithm 6.3 reports "prime" only for genuine primes. The catch, of course, is that running n−3n-3 modular exponentiations is even worse than the n\sqrt{n} gcd computations of the basic test; the exhaustive version is a proof of concept, not a practical algorithm.

Example. Use the Fermat primality test to deduce that 77 is prime.
Here n=7n = 7, so the list is L=2,3,4,5L = 2, 3, 4, 5 and we need a6a^6 in Z7\mathbb{Z}_7 for each of them:

26=64=9×7+1=1,36=(33)2=272=62=36=1,46=(22)6=(26)2=12=1,56=(−2)6=26=1 in Z7.\begin{align*} 2^6 &= 64 \\ &= 9 \times 7 + 1 \\ &= 1, \\ 3^6 &= (3^3)^2 \\ &= 27^2 \\ &= 6^2 \\ &= 36 \\ &= 1, \\ 4^6 &= (2^2)^6 \\ &= (2^6)^2 \\ &= 1^2 = 1, \\ 5^6 &= (-2)^6 \\ &= 2^6 \\ &= 1 \text{ in } \mathbb{Z}_7. \end{align*}

The list has been exhausted and no aa failed. Therefore, 77 is prime. Notice how writing 55 as −2-2 and 44 as 222^2 meant we only ever really computed 262^6; when running these by hand, always look for a way to recycle a power you have already found.

Example. Use the Fermat primality test to deduce that 88 is not prime.
Here n=8n = 8, so the list is L=2,3,4,5,6L = 2,3,4,5,6 and we need a7a^7 in Z8\mathbb{Z}_8. Taking the first entry a=2a = 2,

27=128=16×8=0≠1 in Z8,\begin{align*} 2^7 &= 128 \\ &= 16 \times 8 \\ &= 0 \neq 1 \text{ in } \mathbb{Z}_8, \end{align*}

so we terminate at once. Therefore, 88 is not prime. In this case every entry of the list is a witness, as you can check:

37=(32)3×3=13×3=3≠1,47=(42)3×4=0≠1,57=(52)3×5=13×5=5≠1,67=63×64=0≠1 in Z8,\begin{align*} 3^7 &= (3^2)^3 \times 3 = 1^3 \times 3 = 3 \neq 1, \\ 4^7 &= (4^2)^3 \times 4 = 0 \neq 1, \\ 5^7 &= (5^2)^3 \times 5 = 1^3 \times 5 = 5 \neq 1, \\ 6^7 &= 6^3 \times 6^4 = 0 \neq 1 \text{ in } \mathbb{Z}_8, \end{align*}

using 32=9=13^2 = 9 = 1, 52=25=15^2 = 25 = 1, 42=16=04^2 = 16 = 0 and 63=216=27×8=06^3 = 216 = 27 \times 8 = 0. So whichever aa the algorithm happens to try first, 88 is exposed immediately — which is the behaviour we are hoping for in general.

When the Fermat Test Lies#

The exhaustive test is airtight but slow; the whole point of Fermat's test is that we would like to run only a handful of values of aa and draw a conclusion. That raises the obvious worry: can a composite number pass the Fermat test for some particular aa? It absolutely can, and such numbers get a name.

Note

Definition
For a given n∈Z+n \in \mathbb{Z}^+, if nn is not prime but there is some integer aa such that an−1 mod n=1a^{n-1} \bmod n = 1, we call nn a Fermat pseudoprime to the base aa.

If nn is a Fermat pseudoprime to every base aa that is coprime with nn, we call nn a Carmichael number. That is, nn is a Carmichael number if and only if nn is composite and an−1 mod n=1a^{n-1} \bmod n = 1 for all a∈Zn∗a \in \mathbb{Z}_n^*.

The sequence of Carmichael numbers begins

561, 1105, 1729, 2465, 2821, 6601, …561,\ 1105,\ 1729,\ 2465,\ 2821,\ 6601,\ \dots

Basically, a Fermat pseudoprime is a composite number that is impersonating a prime for one particular base, and a Carmichael number is a composite number that impersonates a prime for every base it possibly could. For a Carmichael number the Fermat primality test is no better than the basic primality test, since the only aa that can ever expose it are the ones with gcd⁡(a,n)≠1\gcd(a,n) \neq 1 — exactly the aa that the basic test was already looking for, and exactly the ones we showed are hopelessly rare.

Example. Show that 341341 is a Fermat pseudoprime to the base 22, but not to the base 33.
First, 341=11×31341 = 11 \times 31, so 341341 is certainly composite. For the base 22, the key observation is

210=1024=3×341+1=1 in Z341,\begin{align*} 2^{10} &= 1024 \\ &= 3 \times 341 + 1 \\ &= 1 \text{ in } \mathbb{Z}_{341}, \end{align*}

and since 340=10×34340 = 10 \times 34 this gives

2340=(210)34=134=1 in Z341.\begin{align*} 2^{340} &= (2^{10})^{34} \\ &= 1^{34} \\ &= 1 \text{ in } \mathbb{Z}_{341}. \end{align*}

So 341341 sails through the Fermat test to the base 22; it is a Fermat pseudoprime to base 22. For the base 33 we repeatedly square:

32=9,34=81,38=812=6561=19×341+82=82,316=822=6724=19×341+245=245,332=2452=60025=176×341+9=9 in Z341.\begin{align*} 3^2 &= 9, \\ 3^4 &= 81, \\ 3^8 &= 81^2 = 6561 = 19 \times 341 + 82 = 82, \\ 3^{16} &= 82^2 = 6724 = 19 \times 341 + 245 = 245, \\ 3^{32} &= 245^2 = 60025 = 176 \times 341 + 9 = 9 \text{ in } \mathbb{Z}_{341}. \end{align*}

Now notice something lovely: 332=9=323^{32} = 9 = 3^2, and gcd⁡(3,341)=1\gcd(3,341) = 1 so 33 is a unit; cancelling 323^2 gives 330=13^{30} = 1, i.e. ord⁡341(3)=30\operatorname{ord}_{341}(3) = 30 or a divisor of it. Since 340=11×30+10340 = 11 \times 30 + 10, we can reduce the exponent modulo the order:

3340=(330)11×310=310=38×32=82×9=738=2×341+56=56≠1 in Z341.\begin{align*} 3^{340} &= (3^{30})^{11} \times 3^{10} \\ &= 3^{10} \\ &= 3^8 \times 3^2 \\ &= 82 \times 9 \\ &= 738 \\ &= 2 \times 341 + 56 \\ &= 56 \neq 1 \text{ in } \mathbb{Z}_{341}. \end{align*}

Therefore, 341341 is a Fermat pseudoprime to base 22 but not to base 33; the single value a=3a = 3 is a witness proving 341341 composite. Passing the Fermat test for one base proves nothing whatsoever; only a failure is conclusive.

Example. Find all integers 1<a<151 < a < 15 such that 1515 is a Fermat pseudoprime to base aa.
Certainly 15=3×515 = 3 \times 5 is composite, so we just need every aa in range with a14=1a^{14} = 1 in Z15\mathbb{Z}_{15}. By the Lemma above we may ignore any aa that is not a unit, so the candidates are

Z15∗∩{2,…,14}={2,4,7,8,11,13,14}.\mathbb{Z}_{15}^* \cap \{2,\dots,14\} = \{2, 4, 7, 8, 11, 13, 14\}.

Now ϕ(15)=ϕ(3)ϕ(5)=2×4=8\phi(15) = \phi(3)\phi(5) = 2 \times 4 = 8, so ord⁡15(a)∣8\operatorname{ord}_{15}(a) \mid 8 for every unit; and a14=1a^{14} = 1 happens exactly when ord⁡15(a)∣14\operatorname{ord}_{15}(a) \mid 14. Combining the two,

ord⁡15(a)∣gcd⁡(8,14)=2,\operatorname{ord}_{15}(a) \mid \gcd(8, 14) = 2,

so a14=1a^{14} = 1 if and only if a2=1a^2 = 1. Squaring each candidate,

22=4≠1,42=16=1,72=49=3×15+4=4≠1,82=64=4×15+4=4≠1,112=121=8×15+1=1,132=169=11×15+4=4≠1,142=(−1)2=1 in Z15.\begin{align*} 2^2 &= 4 \neq 1, \\ 4^2 &= 16 = 1, \\ 7^2 &= 49 = 3 \times 15 + 4 = 4 \neq 1, \\ 8^2 &= 64 = 4 \times 15 + 4 = 4 \neq 1, \\ 11^2 &= 121 = 8 \times 15 + 1 = 1, \\ 13^2 &= 169 = 11 \times 15 + 4 = 4 \neq 1, \\ 14^2 &= (-1)^2 = 1 \text{ in } \mathbb{Z}_{15}. \end{align*}

Therefore, 1515 is a Fermat pseudoprime exactly to the bases a=4,11,14a = 4, 11, 14. Notice the count: 44 of the 88 units pass the test and the other 44 are witnesses, i.e. exactly half — which is the worst case permitted by the next result.

The Randomised Fermat Test#

Running the Fermat primality test up to n−3n-3 times is still hopeless for very large nn. Instead we choose the test integers aa randomly and report whether nn is likely to be prime after a limited number of checks.

Algorithm 6.5 (Fermat primality test, randomised). To test whether a given positive integer nn is prime:

  • Start with a list of integers from 22 up to n−2n-2.
  • Repeat the following up to kk times:
    • Randomly choose (and remove) an integer aa from the list.
    • If gcd⁡(a,n)≠1\gcd(a,n) \neq 1, report that nn is not prime and terminate.
    • If an−1 mod n≠1a^{n-1} \bmod n \neq 1, report that nn is not prime and terminate.
  • If the algorithm has not terminated after kk iterations, report that nn is probably prime and terminate.

The gcd check is strictly speaking redundant — by the Lemma, any aa with gcd⁡(a,n)≠1\gcd(a,n) \neq 1 automatically fails the exponentiation check too — but a gcd is much cheaper than a modular exponentiation, so it is worth doing first.

Everything now hinges on how likely a random aa is to be a witness. This is where the Fermat test decisively beats the basic test.

Note

Lemma
If there is any a∈Zn∗a \in \mathbb{Z}_n^* such that an−1 mod n≠1a^{n-1} \bmod n \neq 1, then there are at least 12ϕ(n)\frac{1}{2}\phi(n) such aa.

Proof. Split the unit group into the elements that pass the test and the elements that fail it:

B={b∈Zn∗:bn−1=1},W={c∈Zn∗:cn−1≠1},\begin{align*} B &= \{b \in \mathbb{Z}_n^* : b^{n-1} = 1\}, \\ W &= \{c \in \mathbb{Z}_n^* : c^{n-1} \neq 1\}, \end{align*}

so that ∣B∣+∣W∣=ϕ(n)|B| + |W| = \phi(n). Assume WW is non-empty and fix one witness a∈Wa \in W. For each b∈Bb \in B, the element c=abc = ab is a product of units and hence a unit, and

cn−1=(ab)n−1=an−1bn−1=an−1×1=an−1≠1 in Zn,\begin{align*} c^{n-1} &= (ab)^{n-1} \\ &= a^{n-1} b^{n-1} \\ &= a^{n-1} \times 1 \\ &= a^{n-1} \neq 1 \text{ in } \mathbb{Z}_n, \end{align*}

so c∈Wc \in W. Moreover the map b↦abb \mapsto ab is injective, since aa is invertible and we can recover b=a−1cb = a^{-1}c; so distinct bb give distinct cc. Hence ∣B∣≤∣W∣|B| \leq |W|, and therefore

ϕ(n)=∣B∣+∣W∣≤2∣W∣,i.e.∣W∣≥12ϕ(n).■\phi(n) = |B| + |W| \leq 2|W|, \quad \text{i.e.} \quad |W| \geq \tfrac{1}{2}\phi(n). \qquad \blacksquare

Basically, the witnesses come for free in bulk: multiply every liar by a single witness and you get that many distinct witnesses back, so witnesses can never be the minority. This is the entire reason the randomised Fermat test is useful — evidence of compositeness is either completely absent or at least half the group, never merely rare.

Consequently each round of the loop, conditional on nn being composite with at least one witness in Zn∗\mathbb{Z}_n^*, has probability at least 12\frac{1}{2} of catching it, and so the algorithm has at worst a

12k chance of incorrectly reporting that n is probably prime.\boxed{\frac{1}{2^k} \text{ chance of incorrectly reporting that } n \text{ is probably prime.}}

Contrast this with the (p−1p)k\left(\frac{p-1}{p}\right)^k worst-case false-positive rate we computed for the randomised basic test on n=p2n = p^2: that quantity barely moves as kk grows, while 12k\frac{1}{2^k} collapses. Twenty rounds already gives a false positive rate below one in a million, and k=100k = 100 makes an error less likely than a hardware fault.

Two warnings before moving on. A report of "probably prime" is never a proof; a composite number that survives kk rounds is still composite, you were just unlucky kk times in a row. And more seriously: the 12k\frac{1}{2^k} bound assumes at least one witness exists in Zn∗\mathbb{Z}_n^*, which is precisely what fails for a Carmichael number. For n=561n = 561 every unit passes, so W=∅W = \varnothing and the argument above says nothing at all; the randomised Fermat test will happily report that 561561 is probably prime no matter how large you make kk, as long as it keeps drawing units.

Example. Run the randomised Fermat test on n=15n = 15 with first random choice a=2a = 2.
First gcd⁡(2,15)=1\gcd(2,15) = 1, so we proceed to the exponentiation. Since 24=16=12^4 = 16 = 1 in Z15\mathbb{Z}_{15},

214=(24)3×22=13×4=4≠1 in Z15.\begin{align*} 2^{14} &= (2^4)^3 \times 2^2 \\ &= 1^3 \times 4 \\ &= 4 \neq 1 \text{ in } \mathbb{Z}_{15}. \end{align*}

Therefore, the test reports (correctly, and after a single round) that 1515 is not prime. Had it instead drawn a=4a = 4, 1111 or 1414 first, that round would have passed and the loop would have continued; but as we counted above, those are only 33 of the 1313 candidates in {2,…,13}\{2,\dots,13\}, so the odds are heavily in our favour.

Certifying Primes with the Lucas Test#

The randomised Fermat test can prove a number composite but can never prove one prime. That is genuinely annoying if you are building a cryptosystem and want a guarantee. The fix is to stop asking for a symptom of primality and start asking for a certificate, and the order of a unit provides exactly the right one.

Recall two facts we already have. First, ϕ(p)=p−1\phi(p) = p-1 if and only if pp is prime, so for any composite nn we must have ϕ(n)<n−1\phi(n) < n-1. Second, if pp is prime then Zp∗\mathbb{Z}_p^* has a primitive element, i.e. a unit whose order is the full ϕ(p)=p−1\phi(p) = p-1. Together these give a clean characterisation.

Note

Theorem
A positive integer n≥2n \geq 2 is prime if and only if there is some a∈Zn∗a \in \mathbb{Z}_n^* such that ord⁡n(a)=n−1\operatorname{ord}_n(a) = n-1.

Proof. (⇒\Rightarrow) Suppose nn is prime. Then ϕ(n)=n−1\phi(n) = n-1, and Zn∗\mathbb{Z}_n^* has a primitive element aa; by definition ord⁡n(a)=ϕ(n)=n−1\operatorname{ord}_n(a) = \phi(n) = n-1.
(⇐\Leftarrow) Suppose ord⁡n(a)=n−1\operatorname{ord}_n(a) = n-1 for some unit aa. By the theorem that order divides the totient, ord⁡n(a)∣ϕ(n)\operatorname{ord}_n(a) \mid \phi(n), and in particular

n−1≤ϕ(n).\begin{align*} n - 1 &\leq \phi(n). \end{align*}

But ϕ(n)\phi(n) counts the integers in {1,2,…,n}\{1,2,\dots,n\} coprime with nn, and nn itself is never one of them (as gcd⁡(n,n)=n>1\gcd(n,n) = n > 1), so ϕ(n)≤n−1\phi(n) \leq n-1 always. Hence ϕ(n)=n−1\phi(n) = n - 1; that is, every one of 1,2,…,n−11, 2, \dots, n-1 is coprime with nn. So nn has no divisor dd with 1<d<n1 < d < n, and therefore nn is prime. ■\blacksquare

Basically, "nn is prime" and "Zn∗\mathbb{Z}_n^* contains an element of order n−1n-1" are the same statement, so finding such an element is a proof of primality. And we already know how to check whether a given aa has full order without computing the order itself — it is the primitive-element test from Order and Primitive Elements.

Algorithm 6.6 (Lucas primality test, randomised). To test whether a given positive integer nn is prime:

  • Start with a list of integers from 22 up to n−2n-2.
  • Repeat the following up to kk times:
    • Randomly choose (and remove) an integer aa from the list.
    • If gcd⁡(a,n)≠1\gcd(a,n) \neq 1, report that nn is not prime and terminate.
    • If an−1 mod n≠1a^{n-1} \bmod n \neq 1, report that nn is not prime and terminate.
    • If an−1pi mod n≠1a^{\frac{n-1}{p_i}} \bmod n \neq 1 for all primes pip_i that divide n−1n-1, report that nn is prime and terminate.
  • If the algorithm has not terminated after kk iterations, report that nn is probably not prime and terminate.

The first three bullets are identical to the randomised Fermat test; all the new content is in the fourth. Why does it detect ord⁡n(a)=n−1\operatorname{ord}_n(a) = n-1? The condition an−1=1a^{n-1} = 1 already forces ord⁡n(a)∣n−1\operatorname{ord}_n(a) \mid n-1. If the order were a proper divisor of n−1n-1, its prime factorisation would be missing at least one copy of some prime pi∣n−1p_i \mid n-1, so we would have ord⁡n(a)∣n−1pi\operatorname{ord}_n(a) \mid \frac{n-1}{p_i} and hence a(n−1)/pi=1a^{(n-1)/p_i} = 1 for that pip_i. So the fourth bullet holding for every pip_i is precisely the statement that no proper divisor of n−1n-1 is the order — i.e. ord⁡n(a)=n−1\operatorname{ord}_n(a) = n-1, and by the characterisation theorem nn is prime.

Notice that the Lucas primality test can in some cases guarantee a number is prime, unlike the (non-exhaustive) Fermat primality test. The price is twofold. First, the Lucas test is only practical when n−1n-1 can be easily factorised — and factorising a 20482048-bit n−1n-1 is exactly the sort of problem we invented these tests to avoid. Second, a report of "probably not prime" is genuinely weak evidence: the test only certifies when the random draw lands on a primitive element, and a prime nn has only ϕ(n−1)\phi(n-1) of those among its n−1n-1 units, which can be a modest fraction. A "prime" verdict from Lucas is a proof; a "probably not prime" verdict is just an admission that no certificate turned up in kk tries.

Example. Use the Lucas primality test to deduce that 77 is prime.
Here n−1=6=2×3n-1 = 6 = 2 \times 3, so the primes dividing n−1n-1 are p1=2p_1 = 2 and p2=3p_2 = 3, and the two exponents to check are

62=3and63=2.\frac{6}{2} = 3 \quad \text{and} \quad \frac{6}{3} = 2.

The candidate list is 2,3,4,52, 3, 4, 5. Suppose the first random draw is a=2a = 2. Then gcd⁡(2,7)=1\gcd(2,7) = 1, and 26=64=12^6 = 64 = 1 in Z7\mathbb{Z}_7 as computed earlier, so the first two checks pass; but

23=8=1 in Z7,\begin{align*} 2^3 &= 8 \\ &= 1 \text{ in } \mathbb{Z}_7, \end{align*}

so the fourth bullet fails at p1=2p_1 = 2 and this round ends with no conclusion. Suppose the next draw is a=3a = 3. Then gcd⁡(3,7)=1\gcd(3,7) = 1, and

32=9=2≠1,33=27=6=−1≠1,36=(33)2=(−1)2=1 in Z7.\begin{align*} 3^2 &= 9 = 2 \neq 1, \\ 3^3 &= 27 = 6 = -1 \neq 1, \\ 3^6 &= (3^3)^2 = (-1)^2 = 1 \text{ in } \mathbb{Z}_7. \end{align*}

So 36=13^6 = 1, while 36/2=33≠13^{6/2} = 3^3 \neq 1 and 36/3=32≠13^{6/3} = 3^2 \neq 1. Therefore, ord⁡7(3)=6=n−1\operatorname{ord}_7(3) = 6 = n-1 and the test reports that 77 is prime — and this time that is a proof, not a probability. As a sanity check, we found in Order and Primitive Elements that the primitive elements of Z7∗\mathbb{Z}_7^* are exactly 33 and 55; those are the only two draws that can certify, and since 22 and 44 both fail, the worst possible ordering needs k≥3k \geq 3 iterations.

Example. Use the Lucas primality test to demonstrate that 2323 is prime, and find the maximum number of iterations the test could need.
Here n−1=22=2×11n - 1 = 22 = 2 \times 11, so the primes dividing n−1n-1 are 22 and 1111, and the exponents to check are

222=11and2211=2.\frac{22}{2} = 11 \quad \text{and} \quad \frac{22}{11} = 2.

Suppose the first draw is a=2a = 2. Then gcd⁡(2,23)=1\gcd(2,23) = 1 and

211=2048=89×23+1=1 in Z23,\begin{align*} 2^{11} &= 2048 \\ &= 89 \times 23 + 1 \\ &= 1 \text{ in } \mathbb{Z}_{23}, \end{align*}

so 222=(211)2=12^{22} = (2^{11})^2 = 1 passes the Fermat check, but 222/2=211=12^{22/2} = 2^{11} = 1 kills the certificate. No conclusion; draw again. Suppose the next draw is a=5a = 5, and build up the powers by squaring:

52=25=2,54=22=4,58=42=16,511=58×52×5=16×2×5=160=6×23+22=22=−1 in Z23.\begin{align*} 5^2 &= 25 = 2, \\ 5^4 &= 2^2 = 4, \\ 5^8 &= 4^2 = 16, \\ 5^{11} &= 5^8 \times 5^2 \times 5 \\ &= 16 \times 2 \times 5 \\ &= 160 \\ &= 6 \times 23 + 22 \\ &= 22 = -1 \text{ in } \mathbb{Z}_{23}. \end{align*}

Hence 522=(511)2=(−1)2=15^{22} = (5^{11})^2 = (-1)^2 = 1, so the Fermat check passes; and the two certificate checks give 511=−1≠15^{11} = -1 \neq 1 and 52=2≠15^2 = 2 \neq 1. Therefore ord⁡23(5)=22=n−1\operatorname{ord}_{23}(5) = 22 = n-1, and the test reports that 2323 is prime.
For the maximum number of iterations, note that the test can only terminate with "prime" when the drawn aa is a primitive element of Z23∗\mathbb{Z}_{23}^*. By the corollary in Order and Primitive Elements there are exactly

ϕ(ϕ(23))=ϕ(22)=ϕ(2)ϕ(11)=1×10=10\phi(\phi(23)) = \phi(22) = \phi(2)\phi(11) = 1 \times 10 = 10

primitive elements. Neither 11 (order 11) nor 22=−122 = -1 (order 22) is one of them, so all 1010 sit inside the candidate list {2,3,…,21}\{2, 3, \dots, 21\}, which has 2020 entries. In the worst case the first 1010 draws are the 1010 non-primitive candidates, and then the 1111th draw is forced to be primitive. Therefore, at most 1111 iterations are needed before the test concludes that 2323 is certainly prime.

Why Lucas Never Certifies a Carmichael Number#

Example. Suppose that when applying the Lucas primality test to 561561, all the chosen integers aa happen to be coprime with 561561. What will the test report?
First set up the numbers. We have

561=3×11×17,560=24×5×7,561 = 3 \times 11 \times 17, \qquad 560 = 2^4 \times 5 \times 7,

so 561561 is composite, the primes dividing n−1=560n - 1 = 560 are 22, 55 and 77, and the three certificate exponents are

5602=280,5605=112,5607=80.\frac{560}{2} = 280, \quad \frac{560}{5} = 112, \quad \frac{560}{7} = 80.

The gcd check. By assumption every drawn aa satisfies gcd⁡(a,561)=1\gcd(a,561) = 1, so this check never fires.
The Fermat check. Let a∈Z561∗a \in \mathbb{Z}_{561}^*, so aa is coprime with each of 33, 1111 and 1717. Fermat's Little Theorem in each prime modulus gives

a2≡1 ⁣ ⁣(mod3),a10≡1 ⁣ ⁣(mod11),a16≡1 ⁣ ⁣(mod17),a^2 \equiv 1 \!\!\pmod 3, \qquad a^{10} \equiv 1 \!\!\pmod{11}, \qquad a^{16} \equiv 1 \!\!\pmod{17},

and since 560=2×280=10×56=16×35560 = 2 \times 280 = 10 \times 56 = 16 \times 35, each of 22, 1010 and 1616 divides 560560. Raising to the appropriate powers,

a560≡1 ⁣ ⁣(mod3),a560≡1 ⁣ ⁣(mod11),a560≡1 ⁣ ⁣(mod17),a^{560} \equiv 1 \!\!\pmod 3, \qquad a^{560} \equiv 1 \!\!\pmod{11}, \qquad a^{560} \equiv 1 \!\!\pmod{17},

and as 3,11,173, 11, 17 are pairwise coprime, the CRT glues these into a560≡1(mod561)a^{560} \equiv 1 \pmod{561}. So the Fermat check never fires either — and this is exactly the computation proving that 561561 is a Carmichael number.
The certificate check. Now run the identical argument with 8080 in place of 560560. Since

80=2×40=10×8=16×5,80 = 2 \times 40 = 10 \times 8 = 16 \times 5,

each of 22, 1010 and 1616 divides 8080 as well, so the same three congruences and the same application of the CRT give

a80=1 in Z561for every a∈Z561∗.a^{80} = 1 \text{ in } \mathbb{Z}_{561} \quad \text{for every } a \in \mathbb{Z}_{561}^*.

But 80=560780 = \frac{560}{7} is one of the three exponents that the fourth bullet requires to be ≠1\neq 1. So for pi=7p_i = 7 the condition fails, for every single unit aa, on every single iteration. The test can therefore never reach the "report that nn is prime" line.
Therefore, the algorithm runs all kk iterations without terminating early and reports that 561561 is probably not prime.

That verdict happens to be correct, but it is worth being very clear about what did and did not just happen. The test has not proved anything about 561561; it has simply failed to find a unit of order 560560, and by the characterisation theorem no such unit can exist, because 561561 is composite. In fact we have shown something sharper: every unit satisfies a80=1a^{80} = 1, so ord⁡561(a)∣80\operatorname{ord}_{561}(a) \mid 80 for all aa, and the largest order in the whole group is 8080 — nowhere near 560560.

Compare this with what the randomised Fermat test does on the same input. Every unit passes a560=1a^{560} = 1, so under the same assumption (all draws coprime with 561561) Fermat runs its kk rounds and reports that 561561 is probably prime, which is simply wrong, no matter how large kk is. This is the punchline of the whole lecture: Fermat asks for a symptom of primality and a Carmichael number can fake it, whereas Lucas asks for a certificate — an element of order exactly n−1n-1 — which a composite number cannot fake, because it does not have one.

Comparing the Three Tests#

All three algorithms in this lecture answer the same question, and they fail in completely different ways; it is worth keeping the differences straight.

Basic (6.2) Fermat (6.3 / 6.5) Lucas (6.6)
Evidence of compositeness a shared factor gcd⁡(a,n)≠1\gcd(a,n) \neq 1 a witness an−1≠1a^{n-1} \neq 1 either of the two on the left
How common is that evidence n−ϕ(n)n\frac{n - \phi(n)}{n}, often tiny 00 or at least 12\frac{1}{2}, never in between 00 or at least 12\frac{1}{2}
Can report "not prime" correctly yes yes yes
Can report "prime" correctly yes, but only after ⌊n⌋\lfloor\sqrt n\rfloor steps only in the exhaustive version (6.3) yes, whenever it reports "prime"
What "no conclusion" means — probably prime probably not prime
Worst-case false positive in kk rounds (p−1p)k\left(\frac{p-1}{p}\right)^k for n=p2n = p^2 12k\frac{1}{2^k}, but useless on Carmichael numbers none; a "prime" report is a proof
Extra input needed none none the prime factorisation of n−1n-1
Bonus hands you an actual factor — hands you a primitive element

So the working method in practice is:

  • If NN is small and you want all primes up to NN, sieve (Algorithm 6.1); it is far cheaper per prime than any individual test.
  • If nn is small, use the basic test (Algorithm 6.2); it is simple, exact, and gives you a factor when it fails.
  • If nn is large, run the randomised Fermat test (Algorithm 6.5) with a decent kk to throw away composites quickly and cheaply.
  • If you need an actual guarantee and you happen to know the factorisation of n−1n-1, finish with the Lucas test (Algorithm 6.6).

Finally, keep the asymmetry of all of this in mind. Proving a number composite is easy — one witness does it, and witnesses are abundant whenever they exist at all. Proving a number prime is hard, because "no factor exists" is a statement about everything, and the only way around it is to produce a positive object like a primitive element instead. That asymmetry is not just a quirk of these algorithms; it is the whole reason RSA works, since generating large primes is comparatively easy while factorising their product is not.