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, BigInteger, a live preview, worked Java 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 |
BigInteger | BigInteger | Best for production code |
| Goal | Pattern |
|---|---|
| Base case | if (n <= 1) return 1; |
| Recurrence | return n * factorial(n - 1) |
| Loop | for (int i = 2; i <= n; i++) result *= i; |
| BigInteger | BigInteger multiply loop |
| Classic values | 0! = 1, 5! = 120, 10! = 3628800 |
| Reject | n < 0 → throw IllegalArgumentException |
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)
BigIntegerOptimized 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 Java programs — recursive, iterative, and BigInteger. Click View Output to reveal sample console results.
Base case + recurrence for interview explanations.
Classic recursive style with input validation.
public class Main {
static long factorialRecursive(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative integers.");
}
if (n <= 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
int number = 5;
long result = factorialRecursive(number);
System.out.println("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 prefer iteration for large n. Exact long results hold through 20!.
Same numeric result with O(1) auxiliary space.
No recursion-depth risk; multiply factors from 2 to n.
public class Main {
static long factorialIterative(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative integers.");
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorialIterative(number));
}
} 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.
Use fixed-width long (use BigInteger beyond 20!) when n may exceed 20.
BigInteger FactorialExact results beyond long — useful once 21! overflows.
import java.math.BigInteger;
public class Main {
static BigInteger factorialBig(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative integers.");
}
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
int[] samples = {0, 1, 5, 10, 20, 25};
for (int n : samples) {
System.out.println(n + "! = " + factorialBig(n));
}
}
} Prefer BigInteger when n may exceed 20. In interviews, write recursive or iterative with long first, then mention overflow and BigInteger.
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 factorialRecursive(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.
BigInteger 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: Java long overflows after 20! — mention BigInteger for larger n.
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 StackOverflowError.
→ Prefer iterative or BigInteger for big n.
Using i < n drops the last factor.
→ Use for (int i = 2; i <= n; i++).
Java long overflows after 20!; talk about BigInteger.
→ Mention arbitrary-precision integers explicitly.
Java long / BigInteger 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 StackOverflowError; iterative code avoids this.
Numbers can be exact but enormous; printing and memory become expensive.
Accept only integers for this interview problem.
i <= nInclusive 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 BigInteger) to ship.
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
BigInteger | 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 BigInteger) 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.
BigIntegeri < 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