- Expand
5·4·3·2·1
Find Factorial in Python
What you’ll learn
- The definition of
n!forn ≥ 0, including0! = 1. - A recursive solution matching classic interview style, plus an iterative equivalent.
- Input validation, recursion-depth limits, and a small live preview.
Overview
Factorial grows very fast. A correct small-n program is easy; a robust one also checks n ≥ 0, explains recursion limits, and offers an iterative fallback.
Two programs
Recursive and iterative Python versions, both producing the same answer.
Live preview
Interactive check for exact values in JavaScript safe integer range.
Rigor
Validates negatives and explains recursion-depth concern for large n.
Prerequisites
Functions, if, multiplication, and basic for loops.
deffunctions,return, and formatted output withprint().- Awareness that recursion in Python has a depth limit; loops are safer for very large
n.
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.
Factorials count permutations: n! is the number of ways to order n distinct objects.
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 (easy to verify and safe to display exactly in JavaScript).
Algorithm
Goal: compute n! for nonnegative n.
Base case
If n ≤ 1, return 1 (covers 0! and 1!).
Recurrence or loop
Otherwise compute n * factorial(n-1), or iteratively multiply factors from 2 to n.
📜 Pseudocode
function factorial(n): // assume n >= 0
if n <= 1:
return 1
return n * factorial(n - 1) Recursive factorial
Classic recursive style with input validation, suitable for interview explanation of base case + recurrence.
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}") Explanation
Each call reduces n until base case 1, then products are built while returning.
Iterative factorial
Same numeric result for n = 5, with O(1) auxiliary space and no recursion-depth risk.
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)}") Explanation
The loop multiplies 1 by every integer from 2 to n. For n in {0, 1}, result stays 1.
Optimization and scaling
Built-in option. Python provides math.factorial(n), optimized and battle-tested for integer inputs.
Large n strategy. Prefer loops or math.factorial over recursion to avoid recursion-depth exceptions.
Interview: explain base case, time complexity, and recursion-depth tradeoff.
❓ FAQ
🔄 Input / output examples
Try these values with either Python example:
| n | n! |
|---|---|
0 | 1 |
1 | 1 |
5 | 120 |
20 | 2432902008176640000 |
Edge cases and pitfalls
Python integers grow automatically, but recursion depth and runtime still matter.
n < 0
Not defined in standard factorial; reject with clear error.
Deep recursion
Large n can raise RecursionError; iterative code avoids this.
Very large factorials
Numbers can be exact but enormous; printing and memory become expensive.
Non-integer input
Accept only integers for this interview problem to keep definition precise.
⏱️ 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!; stack usage is the key difference.
Summary
- Definition:
0! = 1andn! = n·(n-1)!forn ≥ 1. - Code: recursion matches theory; iteration avoids recursion-depth limits.
- Watch-outs: validate negatives and explain why loops are safer for very large
n.
Stirling's approximation is often used to estimate how fast n! grows: n! ∼ √(2πn) · (n/e)n.
8 people found this page helpful
