How to compute the factorial of a number greater than 20 in PHP

1 Answer

0 votes
/*
    This program computes factorials greater than 20 without BCMath.
    It uses a simple big‑integer implementation based on string multiplication.
*/

/*
    Multiply two non‑negative integers represented as strings.
    Classic grade‑school multiplication adapted for PHP strings.
*/
function multiply_strings(string $a, string $b): string
{
    $a = strrev($a);
    $b = strrev($b);

    $result = array_fill(0, strlen($a) + strlen($b), 0);

    for ($i = 0; $i < strlen($a); $i++) {
        for ($j = 0; $j < strlen($b); $j++) {
            $result[$i + $j] += (int)$a[$i] * (int)$b[$j];
        }
    }

    // Handle carries
    for ($i = 0; $i < count($result); $i++) {
        if ($result[$i] >= 10) {
            $carry = intdiv($result[$i], 10);
            $result[$i] %= 10;
            if (!isset($result[$i + 1])) {
                $result[$i + 1] = 0;
            }
            $result[$i + 1] += $carry;
        }
    }

    // Convert back to string
    while (end($result) === 0 && count($result) > 1) {
        array_pop($result);
    }

    return implode('', array_reverse($result));
}

/*
    Compute factorial using string‑based big‑integer arithmetic.
*/
function factorial_big(int $n): string
{
    $result = "1";

    for ($i = 2; $i <= $n; $i++) {
        $result = multiply_strings($result, (string)$i);
    }

    return $result;
}

/*
    Main entry point: read input, compute factorial, print result.
*/
echo "Enter a number greater than 20: ";
$n = intval(trim(fgets(STDIN)));

$result = factorial_big($n);

echo "\nFactorial of {$n} is:\n\n";
echo $result . "\n";




/*
run:

Enter a number greater than 20: 25

Factorial of 25 is:

15511210043330985984000000

*/

 



answered Sep 14 by avibootz
...