Definition
n! & 0!
Product 1…n; empty product gives 0! = 1.
Factorial n! is the product of integers from 1 through n, with 0! = 1. This tutorial covers recursive and iterative solutions, factorialIterative(), a live preview, worked PHP examples, edge cases, and complexity.
n! & 0!
Product 1…n; empty product gives 0! = 1.
n·(n-1)!
Classic recursive interview form.
O(1) space
Loop multiply avoids recursion-depth limits.
Reusable
Best for real code after you can write it yourself.
n ≤ 20
Exact factorials in the browser for small n.
Multiplies
Both styles use Θ(n) multiplications.
Factorial for an integer n ≥ 0 is the product of every integer from 1 through n. By definition, 0! = 1 (the empty product). Example: 5! = 5 × 4 × 3 × 2 × 1 = 120.
Factorials count permutations: n! is the number of ways to order n distinct objects. Values grow extremely fast — a correct small-n program is easy; a robust one also validates n ≥ 0 and prefers loops for large n.
It is the classic interview problem for base cases, recurrence vs loops, and recursion-depth tradeoffs.
Empty product — say it clearly in interviews.
n! = n · (n-1)! for n ≥ 1.
Iteration avoids recursion-depth errors.
Reject n < 0 — factorial is undefined there.
In short: for n ≥ 0, multiply 1 through n (or return 1 when n is 0 or 1).
Given a nonnegative integer n, compute n!.
// 0! = 1
# 5! = 5 * 4 * 3 * 2 * 1 = 120
# 6! = 6 * 5! = 720 | Item | Type | Description |
|---|---|---|
n | int | Nonnegative integer (reject negatives). |
| Return / print | int / text | Exact value of n!. |
function factorial(n): // assume n >= 0
if n <= 1:
return 1
return n * factorial(n - 1) | Method | Idea | Notes |
|---|---|---|
| Recursive | n * factorial(n-1) | Matches theory; O(n) stack |
| Iterative | Multiply 2…n in a loop | O(1) extra space |
| Helper demo | Reusable iterative helper | Same logic, several sample inputs |
| Goal | Pattern |
|---|---|
| Base case | if n <= 1: return 1 |
| Recurrence | return n * factorial(n - 1) |
| Loop | for ($i = 2; $i <= $n; $i++) { $result *= $i; } |
| Helper | factorialIterative($n) |
| Classic values | 0! = 1, 5! = 120, 10! = 3628800 |
| Reject | n < 0 → raise / error |
Three ways to compute n! — pick by clarity and constraints.
n * f(n-1)Teaches base case + recurrence
loop *= iSafer for large n (no stack depth)
factorialIterative()Reuse one tested function in app code
both + tradeoffShow recursion, then mention loop
Reach for factorial when products, permutations, or recursion drills appear.
First recursion problem many candidates see.
Permutations and combinations use n!.
Clear base case and single recursive call.
Natural precursor to recursive sequences.
Validate n ≥ 0 before computing.
Key benefit: one short function that forces clear thinking about base cases, space, and growth.
Exact factorial for 0 ≤ n ≤ 20 (safe to display exactly in JavaScript).
Three complete PHP programs — recursive, iterative, and factorialIterative(). Click View Output to reveal sample console results.
Base case + recurrence for interview explanations.
Classic recursive style with input validation.
<?php
function factorialRecursive(int $n): int
{
if ($n < 0) {
throw new InvalidArgumentException("Factorial is not defined for negative integers.");
}
if ($n <= 1) {
return 1;
}
return $n * factorialRecursive($n - 1);
}
$number = 5;
$result = factorialRecursive($number);
echo "Factorial of $number is: $result" . PHP_EOL;
?> Each call reduces n until the base case 1, then products are built while returning. Stack depth is O(n), so large n can raise stack overflow / depth limits.
Same numeric result with O(1) auxiliary space.
No recursion-depth risk; multiply factors from 2 to n.
<?php
function factorialIterative(int $n): int
{
if ($n < 0) {
throw new InvalidArgumentException("Factorial is not defined for negative integers.");
}
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
$number = 5;
echo "Factorial of $number is: " . factorialIterative($number) . PHP_EOL;
?> The loop multiplies 1 by every integer from 2 to n. For n in {0, 1}, the loop body never runs and result stays 1.
Reuse one helper for several sample inputs.
Compact iterative helper reused for several sample inputs.
<?php
function factorialIterative(int $n): int
{
if ($n < 0) {
throw new InvalidArgumentException("Factorial is not defined for negative integers.");
}
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
foreach ([0, 1, 5, 10, 20] as $n) {
echo $n . "! = " . factorialIterative($n) . PHP_EOL;
}
?> Prefer a tested helper or GMP in real projects. In interviews, write recursive or iterative yourself first, then mention GMP if very large exact values are needed.
Reject n < 0; factorial is not defined for negatives.
If n ≤ 1, return 1 (covers 0! and 1!).
Compute n * factorial(n-1), or multiply 2…n.
Exact product for nonnegative n.
n = 5Trace the recursive expansion for the classic interview value.
| Call | Expression | Returns |
|---|---|---|
f(5) | 5 * f(4) | waits |
f(4) | 4 * f(3) | waits |
f(3) | 3 * f(2) | waits |
f(2) | 2 * f(1) | waits |
f(1) | base | 1 |
| unwind | 2*1 … 5*24 | 120 |
Final answer: 5! = 120.
Where factorial shows up beyond the interview prompt.
Base case, recurrence, and loop tradeoffs.
Example: write factorial(n).
n! counts orderings of n items.
Example: 5 books → 120 orders.
C(n, k) uses factorials in the formula.
Example: n! / (k!(n-k)!).
Single recursive call with a clear stop.
Example: chalkboard unwind of 5!.
Warm-up for recursive series problems.
Example: next page in this chain.
Stirling’s approximation for large-n intuition.
Example: estimate digit growth of n!.
Pro Tip: say “0! = 1” before coding — interviewers listen for that base case.
Why this pattern works well in interviews and classwork.
One recurrence and one base case tell the whole story.
Recursion matches theory; loops scale better.
0, 1, 5, and 20 are easy to verify.
Extract factorialIterative() once, then reuse it everywhere.
Pro Tip: show recursion for the whiteboard, then say you would ship the iterative or builtin version.
Small habits that keep factorial solutions interview-ready.
Call out the empty-product base case first.
Raise a clear error for n < 0.
Avoid recursion-depth exceptions.
Show you know the production shortcut.
120 and 1 catch base-case mistakes fast.
Pro Tip: PHP ints can overflow on large n — mention GMP or arbitrary precision when exact huge values are needed.
Mistakes that commonly break factorial solutions.
Returning 0 or raising for n = 0.
→ Base case: n ≤ 1 returns 1.
Recursive calls never hit a base case for n < 0.
→ Validate and raise early.
Large n hits stack overflow / depth limits.
→ Prefer iterative or factorialIterative() for big n.
Using for ($i = 2; $i < $n; $i++) drops the last factor.
→ Use for ($i = 2; $i <= $n; $i++).
Large n can overflow fixed-width ints; mention GMP for exact big values.
→ Mention arbitrary-precision integers explicitly.
PHP integers can overflow on large n, but recursion depth and runtime still matter.
n < 0Not defined in standard factorial; reject with a clear error.
0! and 1!Both equal 1 — your base case must cover them.
Large n can raise stack overflow / depth limits; iterative code avoids this.
Numbers can be exact but enormous; printing and memory become expensive.
Accept only integers for this interview problem.
for ($i = 2; $i <= $n; $i++)Inclusive end so the last factor is included.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: multiply 1 through n (with 0! = 1); use recursion to explain, loops (or a tested helper) to ship.
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
| Helper demo | O(n) (implementation detail) | O(1) beyond result size |
Both approaches use Θ(n) arithmetic operations for exact n!; stack usage is the key difference. Result size grows with n and is excluded from the “extra space” column above.
Factorial multiplies 1 through n, with 0! = 1 by definition. Use recursion to match the recurrence, prefer an iterative loop (or factorialIterative()) when n grows, and always reject negatives.
Practice the three examples above, then continue to Fibonacci for the next classic sequence problem.
State the base case, explain O(n) time, and call out recursion-depth vs O(1) loop space.
factorialIterative()for ($i = 2; $i < $n; $i++) by mistakeCompute n! the interview-friendly way.
0! = 1
Definitionn·(n-1)!
TheoryO(1) space
Practicen ≥ 0
EdgeΘ(n) ×
AnalysisStirling's approximation is often used to estimate how fast n! grows: n! ∼ √(2πn) · (n/e)n.
Learn iterative and recursive ways to print the Fibonacci sequence.
9 people found this page helpful