PHP, calculating factorial 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 5!=1*2*3*4*5=120
The php code snippet below demonstrates two methods of calculating the factorial of a number, recursive and iterative.

<?php
function recursiveFactorial($num)
{
	if($num < 0) {
		return -1;
	}
    else if($num === 0) {
    	return 1;
    } else {
    	return $num * recursiveFactorial($num-1);
    }
}

function iterativeFactorial($num)
{
    if ($num < 0) {
        return -1;
    }
    else if ($num === 0) {
        return 1;
    }

    $factorial = $num;
    $num = $num-1;
    while ($num > 1) {
        $factorial = $factorial * $num;
        $num = $num -1;
    }
    return $factorial;
}

echo "The factorial of 5 is:" . recursiveFactorial(5) . "\n";
echo "The factorial of 5 is:" . iterativeFactorial(5) . "\n";

Output:

The factorial of 5 is: 120
The factorial of 5 is: 120

Search within Codexpedia

Custom Search

Search the entire web

Custom Search