Purpose: Decide whether a Mersenne numberMp=2p−1 (with p prime) is prime, deterministically, in O(p2) bit operations — or O(plogploglogp) with FFT multiplication.
The Test
Define the sequence s0=4,si+1=si2−2.
Then for odd prime p: Mp=2p−1 is prime⟺sp−2≡0(modMp).
Code
def lucas_lehmer(p): if p == 2: return True # M_2 = 3 is prime M = (1 << p) - 1 s = 4 for _ in range(p - 2): s = (s * s - 2) % M return s == 0
Reduction without division
Because 2p≡1(modMp), reducing mod Mp is a shift-and-add:
def mod_mersenne(x, p, M): while x > M: x = (x & M) + (x >> p) return x - M if x == M else x
This is why the test is so cheap per step — no division at all.
Complexity
p−2 iterations, each one squaring of a p-bit number
Schoolbook: O(p2) per step → O(p3) total
With FFT/IBDWT multiplication: O~(p) per step → O~(p2) total
For p≈8⋅107 (the current record region) this is days of GPU time per candidate — which is exactly what GIMPS, the Great Internet Mersenne Prime Search, distributes across volunteers.
Why It Works (sketch)
Work in Z[3] and set ω=2+3, ωˉ=2−3, so ωωˉ=1. Then si=ω2i+ωˉ2i.
The condition sp−2≡0(modMp) is equivalent to ω2p−1≡−1, which says the order of ω in the multiplicative group modulo Mp is exactly 2p. Such an element can exist only if the group is large enough, forcing Mp to be prime; conversely, when Mp is prime, 3 is a quadratic non-residue mod Mp (since Mp≡7(mod12)), and a Frobenius argument gives the required order.
Facts worth knowing
Mp can only be prime if p itself is prime (if p=ab, then 2a−1∣2p−1). The converse fails: M11=2047=23⋅89.
Only 52 Mersenne primes are known. The largest known prime has been a Mersenne prime almost continuously since 1952, entirely because of this test.
Every even perfect number is 2p−1(2p−1) with Mp prime (Euclid-Euler), so Mersenne primes and even perfect numbers are in bijection.
Variants / Use Cases
Lucas-Lehmer-Riesel test — the analogue for numbers of the form k⋅2n−1
Pépin’s test — the corresponding deterministic test for Fermat numbers 22n+1
Miller-Rabin — the general-purpose test; use it for anything not of Mersenne form