PHP Program to Find Factorial Using Recursion
function factorial($n) { return $n <= 1 ? 1 : $n * factorial($n - 1); } and calling it with the desired number.Examples
How to Think About It
Algorithm
Code
<?php function factorial($n) { if ($n <= 1) { return 1; } else { return $n * factorial($n - 1); } } echo factorial(5); // Output: 120
Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
5 > 1, so return 5 * factorial(4)
Call factorial(4)
4 > 1, so return 4 * factorial(3)
Call factorial(3)
3 > 1, so return 3 * factorial(2)
Call factorial(2)
2 > 1, so return 2 * factorial(1)
Call factorial(1)
1 <= 1, so return 1
Return values multiply back
2 * 1 = 2, 3 * 2 = 6, 4 * 6 = 24, 5 * 24 = 120
| Call | Return Value |
|---|---|
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The function stops calling itself when the input is 1 or less, returning 1 because factorial of 0 or 1 is 1.
Step 2: Recursive Call
For numbers greater than 1, the function calls itself with the number minus one, building the factorial step by step.
Step 3: Multiplying Results
Each recursive call returns a value that is multiplied by the current number, combining to form the factorial.
Alternative Approaches
<?php function factorial_iterative($n) { $result = 1; for ($i = 2; $i <= $n; $i++) { $result *= $i; } return $result; } echo factorial_iterative(5); // Output: 120
<?php // Requires GMP extension echo gmp_fact(5); // Output: 120
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative approach uses constant space and is generally faster, while recursion is simpler to write but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, small inputs |
| Iterative | O(n) | O(1) | Large inputs, performance |
| Built-in (gmp_fact) | Optimized | Optimized | Best performance if GMP available |