- Expand
5·4·3·2·1
Find Factorial in PHP
What you’ll learn
- The definition of
n!forn ≥ 0, including0! = 1. - A recursive solution matching classic interview style, plus an iterative equivalent.
- Large-value notes, input validation, and a small live preview.
Overview
Factorial grows faster than exponentials. A robust interview answer handles n ≥ 0, explains 0! = 1, and compares recursion with iteration.
Two programs
Recursive (5! = 120) and iterative with the same result.
Live preview
Exact integers for 0 ≤ n ≤ 20 in this widget.
Rigor
Guards for negative input and notes for very large n.
Prerequisites
Functions, if, multiplication, and optional for loops.
- Basic PHP syntax:
<?php,function, type hints, andecho. - Awareness that factorial values grow quickly and may exceed normal integer ranges.
What is factorial?
For an integer n ≥ 0, n! is the product of every integer from 1 through n. When n = 0, that is the empty product, defined as 1, so 0! = 1.
Factorials count permutations: n! is the number of ways to order n distinct objects. They appear in series, combinations, and probability.
Formal definition
Define 0! = 1 and, for n ≥ 1, n! = n · (n-1)!. Equivalently n! = ∏k=1n k.
5!5 × 4 × 3 × 2 × 1 = 120.
Intuition
- Step
6 · 5!
Takeaway: each increment of n multiplies the previous factorial by n, which is why values explode in size.
Live preview
Exact factorial for 0 ≤ n ≤ 20 in this preview.
Algorithm
Goal: compute n! for nonnegative n in PHP.
Base case
If n ≤ 1, return 1 (covers 0! and 1!).
Recurrence or loop
Otherwise multiply n by (n-1)!, or use a loop multiplying factors 2..n.
📜 Pseudocode
function factorial(n): // assume n >= 0
if n <= 1:
return 1
return n * factorial(n - 1)Recursive factorial
Classic recursive style with a small input guard for nonnegative values.
<?php
function factorialRecursive(int $num): int
{
if ($num === 0 || $num === 1) {
return 1;
}
return $num * factorialRecursive($num - 1);
}
$number = 5;
if ($number < 0) {
echo "Factorial is not defined for negative integers here.\n";
} else {
$result = factorialRecursive($number);
echo "Factorial of {$number} is: {$result}\n";
}
?>Explanation
Each recursive call reduces $num until the base case, then multiplies while returning back up the call stack.
Iterative factorial
Same numeric result for n = 5, with O(1) auxiliary space and no recursion depth concerns.
<?php
function factorialIterative(int $n): int
{
$r = 1;
for ($i = 2; $i <= $n; $i++) {
$r *= $i;
}
return $r;
}
$number = 5;
if ($number < 0) {
echo "Factorial is not defined for negative integers here.\n";
} else {
echo "Factorial of {$number} is: " . factorialIterative($number) . "\n";
}
?>Explanation
The loop multiplies 1 by every integer from 2 to n. For n in {0,1}, it stays 1.
Optimization and scaling
Bigger values. Use arbitrary-precision methods when exact integer factorials exceed normal ranges.
Advanced methods. Prime-based or split-recursion methods reduce large multiplication overhead, but are beyond basic interviews.
Interview: state input validation, mention growth/overflow, and compare recursion depth vs loop.
❓ FAQ
🔄 Input / output examples
Change $number in either example (within 0..20 for exact preview values).
| n | n! |
|---|---|
0 | 1 |
1 | 1 |
5 | 120 |
20 | 2432902008176640000 |
Edge cases and pitfalls
Factorial grows quickly, so always validate input and mention limits for large values.
n < 0
Not part of the standard factorial definition; reject such inputs in this tutorial.
Very large n
Values become huge quickly; you need arbitrary-precision techniques for exact large results.
Deep recursion
Large recursion depth can fail; use an iterative loop when depth is a concern.
0! = 1
Do not forget this definition; it is essential for both recursive and iterative correctness.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
Both approaches use Θ(n) arithmetic operations for exact n!; the stack usage differs.
Summary
- Definition:
0! = 1andn! = n·(n-1)!forn ≥ 1. - Code: recursion matches the classic template; iteration saves call-stack depth.
- Watch-outs: negatives undefined, fast growth for large
n, and recursion depth limits.
Stirling's approximation describes how fast n! grows: asymptotically n! ∼ √(2πn) · (n/e)n. It is standard in analysis even when exact integers become very large.
8 people found this page helpful
