Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to calculate a factorial

Short answer

Multiply the numbers from 1 to N:

<?php
 
echo array_product(range(1, 5));

Output:

120

With a loop

A function that checks its argument:

<?php
 
function factorial(int $n): int
{
    if ($n < 0) {
        throw new InvalidArgumentException('The number must not be negative');
    }
 
    $result = 1;
 
    for ($i = 2; $i <= $n; $i++) {
        $result *= $i;
    }
 
    return $result;
}
 
echo factorial(0), ' ', factorial(10);

Output:

1 3628800

Large numbers

A factorial grows very fast and soon stops fitting into an integer: after 20 on 64-bit systems, and already after 12 on 32-bit ones. On overflow the result becomes a float and loses precision:

<?php
 
var_dump(is_int(array_product(range(1, 12))));
var_dump(is_int(array_product(range(1, 25))));

Output:

bool(true)
bool(false)

Functions used in this recipe

  • array_product — Multiplies the elements of an array.
  • range — Creates an array holding a sequence of values.
  • is_float — Checks whether a value is a float.

Thanks for reading!

Donate to the site — we work hard for you.