PHP Program to Find Factorial of a Number
for ($i = 1; $i <= $n; $i++) { $factorial *= $i; } to multiply all numbers from 1 to $n.Examples
How to Think About It
Algorithm
Code
<?php $n = 5; $factorial = 1; for ($i = 1; $i <= $n; $i++) { $factorial *= $i; } echo "Factorial of $n is $factorial"; ?>
Dry Run
Let's trace the factorial calculation for input 5 through the code.
Initialize variables
$n = 5, $factorial = 1
First loop iteration
$i = 1, $factorial = 1 * 1 = 1
Second loop iteration
$i = 2, $factorial = 1 * 2 = 2
Third loop iteration
$i = 3, $factorial = 2 * 3 = 6
Fourth loop iteration
$i = 4, $factorial = 6 * 4 = 24
Fifth loop iteration
$i = 5, $factorial = 24 * 5 = 120
Loop ends
Final factorial = 120
| Iteration | i | factorial |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 6 |
| 4 | 4 | 24 |
| 5 | 5 | 120 |
Why This Works
Step 1: Start with 1
We set $factorial = 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply in loop
Each loop multiplies $factorial by the current number $i, building the product step by step.
Step 3: Result after loop
After the loop finishes, $factorial holds the product of all numbers from 1 to $n, which is the factorial.
Alternative Approaches
<?php function factorial($n) { if ($n <= 1) return 1; return $n * factorial($n - 1); } $n = 5; echo "Factorial of $n is " . factorial($n); ?>
<?php $n = 5; $factorial = 1; $i = 1; while ($i <= $n) { $factorial *= $i; $i++; } echo "Factorial of $n is $factorial"; ?>
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so the time grows linearly with the input number.
Space Complexity
Only a few variables are used, so space stays constant regardless of input size.
Which Approach is Fastest?
Both loop and recursion have O(n) time, but loops use less memory and avoid function call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(1) | Simple and efficient for all inputs |
| Recursive | O(n) | O(n) | Elegant but risky for large inputs |
| While loop | O(n) | O(1) | Alternative loop style, same efficiency |