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, math.factorial, a live preview, worked Python 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.
Builtin
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 |
math.factorial | Builtin | Best for production code |
| Goal | Pattern |
|---|---|
| Base case | if n <= 1: return 1 |
| Recurrence | return n * factorial(n - 1) |
| Loop | for i in range(2, n + 1): result *= i |
| Builtin | math.factorial(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)
math.factorialOptimized and battle-tested
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 Python programs — recursive, iterative, and math.factorial. Click View Output to reveal sample console results.
Base case + recurrence for interview explanations.
Classic recursive style with input validation.
def factorial_recursive(n: int) -> int:
if n < 0:
raise ValueError("Factorial is not defined for negative integers.")
if n <= 1:
return 1
return n * factorial_recursive(n - 1)
number = 5
result = factorial_recursive(number)
print(f"Factorial of {number} is: {result}") 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 RecursionError.
Same numeric result with O(1) auxiliary space.
No recursion-depth risk; multiply factors from 2 to n.
def factorial_iterative(n: int) -> int:
if n < 0:
raise ValueError("Factorial is not defined for negative integers.")
result = 1
for i in range(2, n + 1):
result *= i
return result
number = 5
print(f"Factorial of {number} is: {factorial_iterative(number)}") The loop multiplies 1 by every integer from 2 to n. For n in {0, 1}, the range is empty and result stays 1.
Use the standard library when you do not need to reinvent the wheel.
math.factorialOptimized and battle-tested for integer inputs.
import math
for n in (0, 1, 5, 10, 20):
print(f"{n}! = {math.factorial(n)}") Prefer math.factorial in real projects. In interviews, write recursive or iterative yourself first, then mention the builtin.
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.
math.factorial is ready for production use.
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: Python ints do not overflow like C — talk about time/memory instead of fixed-width overflow.
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 RecursionError.
→ Prefer iterative or math.factorial for big n.
Using range(2, n) drops the last factor.
→ Use range(2, n + 1).
Python ints grow; talk about time/memory instead.
→ Mention arbitrary-precision integers explicitly.
Python integers grow automatically, 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 RecursionError; iterative code avoids this.
Numbers can be exact but enormous; printing and memory become expensive.
Accept only integers for this interview problem.
range(2, n + 1)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 math.factorial) to ship.
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
math.factorial | 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 math.factorial) 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.
math.factorialrange(2, n) 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