Skip to content

Primality Tests

Given an integer nn, we can check numbers up to n\sqrt{n} to find if a number divides nn. If there is such a number, nn is composite. If not, nn is a prime. This gives the solution in O(n)O(\sqrt{n}).

Now we know how to generate prime numbers fast. How about primality testing?

Naive solutions first. Given an integer nn, we can check numbers up to n\sqrt{n} to find if a number divides nn. If there is such a number, nn is composite. If not, nn is a prime. This gives the solution in O(n)O(\sqrt{n}).

Here’s a “solution” in O(clnn)O(c\ln n) using the fast exponentiation we will talk about in the next section. It’s called Miller-Rabin Primality Test. I’ll introduce the deterministic version. We probably (hopefully) won’t see stuff like n>4109n> 4 \cdot 10^9 in contests.

Here’s the sketch of the algorithm. Choose some set of aa. We will run the algorithm with different aas, and the more aas we run this algorithm with, the more accurate this primality test is going to be.

Decompose n1n-1 as 2sd2^s \cdot d. Then check if the following holds. ad≢1(modn) and a2rd≢1(modn) for all r[0,s1]a^d \not\equiv 1 \pmod{n} \text{ and }a^{2^rd} \not\equiv -1 \pmod{n} \text{ for all } r \in [0,s-1]If there is an aa that satisfies this, nn is composite. If not, nn is a prime.

List for sufficient checks (deterministic)

Section titled “List for sufficient checks (deterministic)”
  • n<4.7109n<4.7 \cdot 10^9a=2,7,61a=2,7,61
  • n<264n<2^{64}a=2,3,5,7,11,13,17,19,23,29,31,37a=2,3,5,7,11,13,17,19,23,29,31,37