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.

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.