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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?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