Introduction
Number theory for PHP, with primes, factorization, modular arithmetic and more, for integers of any size.
Requirements#
The library builds on phpmath/biginteger and uses the GMP extension for the heavy work.
- PHP 8.4 or newer
- The
gmpextension phpmath/biginteger3.0 or newer (installed automatically)
Installation#
Install the library with Composer. This also installs phpmath/biginteger.
composer require phpmath/number-theory
A first example#
Numbers are BigInteger objects, so there is no limit on their size. This example factors a number that does not fit in 64 bits and then asks for its totient (the count of numbers up to it that share no factor with it).
use PHPMath\BigInteger\BigInteger;
use PHPMath\NumberTheory\Factorizer;
use PHPMath\NumberTheory\Totient;
$number = new BigInteger('18446744073709551617');
echo Factorizer::factorize($number); // 274177 * 67280421310721
echo Totient::of($number)->value(); // 18446676793287966720
Neither call changed $number. Every operation returns a new value.
Where to go next#
Start with the core concepts, or jump straight to the topic you need.
Core conceptsStatic helpers, immutable results, number types and errors.DivisibilityGCD, LCM, coprime numbers and the extended Euclidean algorithm.Modular arithmeticPowers, inverses and the Chinese remainder theorem.Primes and sievingPrimality tests, the next prime and the sieve.FactorizationPrime factors, divisors and the totient.API referenceEvery method with its parameters and errors.