Pépin's test returns true exactly when 2^(2^k) + 1 is prime full
This proof shows: correctness, termination.
We use the pseudocode PEPIN(k) of the page, for an integer k≥0, with F=Fk=22k+1 and e=2k. So F−1=2e and (F−1)/2=2e−1.
Termination. The loop of line L4 runs e−1 times, and each pass does one squaring and one reduction. The reduction ends (Lemma 1). So the call ends.
Lemma 1 (the reduction). Let x≥0 and write x=h⋅2e+ℓ with 0≤ℓ<2e. Then x≡ℓ−h(modF). If moreover x≤(F−1)2, then −F<ℓ−h<F, so ℓ−h, plus F if it is negative, is xmodF.
Proof. 2e=F−1≡−1(modF), so h⋅2e+ℓ≡ℓ−h. If x≤(F−1)2=22e, then h=⌊x/2e⌋≤2e=F−1, so ℓ−h≥−(F−1)>−F. Also ℓ−h≤ℓ<2e<F. So ℓ−h lies in (−F,F) and is congruent to x, and adding F when it is negative gives the residue in [0,F). □
Lemma 2 (the loop invariant). For k≥1, after the i-th pass of line L5, 0≤x<F and x≡32i(modF). So after the loop, x=3(F−1)/2modF.
Proof. Before the loop, x=3=320 and 3<F since F≥5. If x≡32i with 0≤x<F, then x2≡32i+1 and x2≤(F−1)2, so by Lemma 1 line L5 stores its residue in [0,F). After e−1 passes, x≡32e−1=3(F−1)/2. □
Lemma 3 (the congruence implies primality). Let k≥1. If 3(F−1)/2≡−1(modF), then F is prime.
Proof. Let q be a prime factor of F. Reducing modulo q gives 3(F−1)/2≡−1(modq). If q=3, the left side is 0 and the right side is 2 modulo 3, which is impossible; so q=3 and 3 is a unit modulo q. Squaring gives 3F−1≡1(modq). Let d be the multiplicative order of 3 modulo q. Then d∣F−1=2e, so d is a power of 2. If d∣(F−1)/2=2e−1, then 3(F−1)/2≡1(modq), so 1≡−1 and q=2, but F is odd. Hence d=2e=F−1. By Fermat's little theorem, d∣q−1, so q≥F. As q∣F, q=F, and F is prime. □
Lemma 4 (primality implies the congruence). Let k≥1. If F is prime, then 3(F−1)/2≡−1(modF).
Proof. As k≥1, e≥2, so 4∣2e and F≡1(mod4). As e is even, 2e=4e/2≡1(mod3), so F≡2(mod3); in particular F=3, and F is an odd prime with 3∤F. By the law of quadratic reciprocity, since F≡1(mod4),
(F3)=(3F)=(32)=−1, the last because the squares modulo 3 are 0 and 1. By Euler's criterion, 3(F−1)/2≡(F3)=−1(modF). □
Theorem. For each integer k≥0, PEPIN(k) returns true if and only if Fk is prime.
Proof. If k=0, then F0=3 is prime, and line L1 returns true. Let k≥1. By Lemma 2, line L6 returns true if and only if 3(F−1)/2modF=F−1, that is, 3(F−1)/2≡−1(modF). By Lemmas 3 and 4, this holds if and only if F is prime. ■