Purpose: Decide whether a Mersenne number (with prime) is prime, deterministically, in bit operations — or with FFT multiplication.

The Test

Define the sequence

Then for odd prime :

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 , reducing mod 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

  • iterations, each one squaring of a -bit number
  • Schoolbook: per step → total
  • With FFT/IBDWT multiplication: per step → total

For (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 and set , , so . Then

The condition is equivalent to , which says the order of in the multiplicative group modulo is exactly . Such an element can exist only if the group is large enough, forcing to be prime; conversely, when is prime, 3 is a quadratic non-residue mod (since ), and a Frobenius argument gives the required order.

Facts worth knowing

  • can only be prime if itself is prime (if , then ). The converse fails: .
  • 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 with 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
  • Pépin’s test — the corresponding deterministic test for Fermat numbers
  • Miller-Rabin — the general-purpose test; use it for anything not of Mersenne form
  • Primality Testing — the topic page