Site icon T4Tutorials.com

Factorial PHP recursively and iteratively

Let’s see the Factorial program in PHP recursively and iteratively.

The factorial of a given positive integer is the product of all positive integers less than and equal to the given positive integer. For example, the factorial of 4!=1*2*3*4=24
The example with PHP code is demonstrated below by calculating the factorial of a number, iteratively and recursively.

<?php
function recursiveFactorial($T4Tutorials_Number)
{
    if($T4Tutorials_Number < 0) {
        return -1;
    }
    else if($T4Tutorials_Number === 0) {
        return 1;
    } else {
        return $T4Tutorials_Number * recursiveFactorial($T4Tutorials_Number-1);
    }
}
 
function iterativeFactorial($T4Tutorials_Number)
{
    if ($T4Tutorials_Number < 0) {
        return -1;
    }
    else if ($T4Tutorials_Number === 0) {
        return 1;
    }
 
    $factorial = $T4Tutorials_Number;
    $T4Tutorials_Number = $T4Tutorials_Number-1;
    while ($T4Tutorials_Number > 1) {
        $factorial = $factorial * $T4Tutorials_Number;
        $T4Tutorials_Number = $T4Tutorials_Number -1;
    }
    return $factorial;
}
 
echo "The factorial of 5 is:" . recursiveFactorial(5) . "\n";
echo "The factorial of 5 is:" . iterativeFactorial(5) . "\n";
Output:

Output

The factorial of 4 is: 24
The factorial of 4 is: 24

Exit mobile version