Current Location: Home> Latest Articles> Tutorial: Implementing Lucas-Lehmer Primality Test for Large Integers with PHP and GMP

Tutorial: Implementing Lucas-Lehmer Primality Test for Large Integers with PHP and GMP

M66 2025-10-09

Introduction

In number theory, the Lucas-Lehmer primality test is an efficient method to determine whether a Mersenne number is prime. In this article, we will use PHP and the GMP extension (GNU Multiple Precision Arithmetic Library) to implement the Lucas-Lehmer test, providing complete code examples.

What is the Lucas-Lehmer Primality Test?

The Lucas-Lehmer test is specifically designed to check if numbers of the form M = 2^n - 1, called Mersenne numbers, are prime, where n is a positive integer greater than 1. The test relies on the Lucas-Lehmer sequence, iteratively calculating each element and checking if the last element is zero to determine primality.

Performing Lucas-Lehmer Test with PHP and GMP

Installing GMP Extension

PHP's built-in functions cannot handle extremely large integer calculations, so the GMP extension is required. You can install PHP with GMP enabled or activate the GMP extension in an existing PHP environment.

Writing the Lucas-Lehmer Test Function

function lucasLehmerTest($n)
{
    $s = '4';
    $m = gmp_pow('2', $n) - '1';

    for ($i = 1; $i < $n - 1; $i++) {
        $s = gmp_mod(gmp_pow($s, 2) - 2, $m);
    }

    if ($s == '0') {
        return true;
    }

    return false;
}

Explanation:

  • $n: Exponent of the Mersenne number.
  • $s: Initial value of the Lucas-Lehmer sequence.
  • $m: The Mersenne number itself.

The function calculates 2^$n - 1 using gmp_pow to get $m, then iterates $n-1 times to compute the Lucas-Lehmer sequence. The final element determines the number's primality.

Calling the Lucas-Lehmer Test Function

$exponents = [2, 3, 5, 7, 13, 17];

foreach ($exponents as $exponent) {
    $result = lucasLehmerTest($exponent);

    if ($result) {
        echo "2^$exponent - 1 is a prime number.";
    } else {
        echo "2^$exponent - 1 is not a prime number.";
    }
}

Explanation:

An array $exponents contains multiple exponent values. We loop through each exponent with foreach, call the Lucas-Lehmer test, and output whether each Mersenne number is prime.

Conclusion

Using PHP with the GMP extension, it's easy to implement the Lucas-Lehmer primality test and check large integers for primality. For large Mersenne numbers, the Lucas-Lehmer algorithm is efficient and can quickly determine primality. The provided code examples serve as a practical reference.

References

  • Lucas–Lehmer primality test. Wikipedia, The Free Encyclopedia. URL: https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
  • GMP Manual. PHP. URL: https://www.php.net/manual/en/book.gmp.php