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 C solutions, unsigned long long overflow limits, a live preview, worked C 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 call-stack depth growth.
n ≤ 20
unsigned long long holds exact n! only through 20!.
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 C program also validates n ≥ 0, watches unsigned long long overflow, and prefers loops for large n.
It is the classic interview problem for base cases, recurrence vs loops, stack depth, and fixed-width integer overflow in C.
Empty product — say it clearly in interviews.
n! = n · (n-1)! for n ≥ 1.
Iteration avoids stack-depth growth.
Exact unsigned long long stops at n = 20.
In short: for n ≥ 0, multiply 1 through n (or return 1 when n is 0 or 1) — and bound n before silent unsigned wrap.
Given a nonnegative integer n, compute n! within a chosen numeric type.
/* 0! = 1
* 5! = 5 * 4 * 3 * 2 * 1 = 120
* 6! = 6 * 5! = 720 */ | Item | Type | Description |
|---|---|---|
n | int | Nonnegative integer (reject negatives). |
| Return / print | unsigned long long / text | Exact value of n! when it fits (typically n ≤ 20). |
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 |
| Overflow-aware | Reject n > 20 for ull | Avoids silent wrap |
| Goal | Pattern |
|---|---|
| Base case | if (n <= 1) return 1; |
| Recurrence | return (unsigned long long)n * factorial(n - 1); |
| Loop | for (i = 2; i <= n; ++i) r *= (unsigned long long)i; |
printf("%llu\n", result); | |
| Classic values | 0! = 1, 5! = 120, 20! = 2432902008176640000 |
| Reject | n < 0 or n > 20 for exact ull |
Three angles interviewers expect — clarity, stack, and integer width.
n * f(n-1)Teaches base case + recurrence
loop *= iSafer stack for larger n
n <= 20Keeps results exact in ull
both + overflowShow recursion, then loop + limits
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.
C forces you to discuss silent wrap vs big integers.
Key benefit: one short function that forces clear thinking about base cases, stack space, and type width.
Exact factorial for 0 ≤ n ≤ 20 (matches a typical unsigned long long ceiling before wrap).
Three complete C programs — recursive, iterative, and a small table of known values with overflow guards. Click View Output to reveal sample console results.
Base case + recurrence for interview explanations.
Classic recursive style with negative and overflow checks for unsigned long long.
#include <stdio.h>
#define FACT_MAX_ULL 20
unsigned long long calculate_factorial(int num) {
if (num == 0 || num == 1) {
return 1u;
}
return (unsigned long long)num * calculate_factorial(num - 1);
}
int main(void) {
int number = 5;
if (number < 0) {
printf("Factorial is not defined for negative integers here.\n");
return 0;
}
if (number > FACT_MAX_ULL) {
printf("n too large for exact unsigned long long in this demo (max %d).\n", FACT_MAX_ULL);
return 0;
}
unsigned long long result = calculate_factorial(number);
printf("Factorial of %d is: %llu\n", number, result);
return 0;
} Each call shrinks num until the base case; products bubble back up. Cast num before multiplying so intermediate products stay in unsigned long long. Stack depth is O(n).
Same numeric result with O(1) auxiliary space.
No call-stack depth proportional to n; multiply factors from 2 to n.
#include <stdio.h>
#define FACT_MAX_ULL 20
unsigned long long factorial_iter(int n) {
unsigned long long r = 1u;
int i;
for (i = 2; i <= n; ++i) {
r *= (unsigned long long)i;
}
return r;
}
int main(void) {
int number = 5;
if (number < 0) {
printf("Factorial is not defined for negative integers here.\n");
return 0;
}
if (number > FACT_MAX_ULL) {
printf("n too large for exact unsigned long long in this demo (max %d).\n", FACT_MAX_ULL);
return 0;
}
printf("Factorial of %d is: %llu\n", number, factorial_iter(number));
return 0;
} The loop multiplies 1 by every integer from 2 through n. For n in {0, 1}, the loop body never runs and r stays 1.
Spot-check classics that fit in unsigned long long.
Handy for verifying 0!, 1!, 5!, 10!, and the 20! ceiling.
#include <stdio.h>
unsigned long long factorial_iter(int n) {
unsigned long long r = 1u;
int i;
for (i = 2; i <= n; ++i) {
r *= (unsigned long long)i;
}
return r;
}
int main(void) {
int values[] = {0, 1, 5, 10, 20};
int i;
for (i = 0; i < 5; ++i) {
int n = values[i];
printf("%d! = %llu\n", n, factorial_iter(n));
}
return 0;
} Reuse the iterative helper and print a short checklist of values. In interviews, knowing 5! = 120 and that 21! overflows 64-bit unsigned is a strong follow-up answer.
Reject n < 0; optionally reject n > 20 for exact ull.
If n ≤ 1, return 1 (covers 0! and 1!).
Compute n * factorial(n-1), or multiply 2…n.
Exact product when the type can hold it.
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” and “21! overflows 64-bit unsigned” before coding — interviewers listen for both.
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 on the stack.
0, 1, 5, and 20 are easy to verify by hand.
C lets you demonstrate awareness of silent unsigned wrap.
Pro Tip: show recursion for the whiteboard, then say you would ship the iterative version with an n ≤ 20 guard (or a big-int library).
Small habits that keep factorial solutions interview-ready in C.
Call out the empty-product base case first.
Print an error and return for n < 0.
Avoid deep call stacks even when the type still fits.
Promote to unsigned long long so products do not truncate early.
120 and 1 catch base-case mistakes fast.
Pro Tip: unsigned overflow wraps silently in C — bound n or check before multiply, never assume wrap is “just wrong.”
Mistakes that commonly break factorial solutions in C.
Returning 0 or erroring for n = 0.
→ Base case: n ≤ 1 returns 1.
Recursive calls never hit a base case for n < 0.
→ Validate and reject early.
21! exceeds 264−1; unsigned wrap is silent.
→ Cap at n ≤ 20 or use big-integer libraries.
int for the Result13! already exceeds 32-bit signed int.
→ Prefer unsigned long long for small exact factorials.
Even when n fits, stack frames may not.
→ Prefer iterative for moderately large n.
Unsigned overflow is silent in C; always bound n or check products before they wrap.
n < 0Not defined in standard factorial; reject instead of recursing.
0! and 1!Both equal 1 — your base case must cover them.
21! and beyondExceeds 264−1; widen to big integers or change the problem.
Very large n can overflow the call stack before the integer type does.
int result13! already exceeds 32-bit int; prefer wide unsigned.
%lluMatch the conversion specifier to unsigned long long.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
unsigned long long caps near 20!; silent unsigned wrap.Quick Takeaway: multiply 1 through n (with 0! = 1); use recursion to explain, loops to ship, and bound n for exact ull.
| 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!; only the hidden stack differs. Result bit-width 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 when n grows, validate negatives, and keep exact unsigned long long results within n ≤ 20.
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 stack depth vs O(1) loop space plus silent unsigned wrap.
unsigned long long + %lluintCompute n! the interview-friendly way in C.
0! = 1
Definitionn·(n-1)!
TheoryO(1) space
Practicen ≥ 0, n ≤ 20
EdgeΘ(n) ×
AnalysisStirling's approximation describes how fast n! grows: asymptotically n! ∼ √(2πn) · (n/e)n. It is standard in analysis even when the exact integer no longer fits in fixed-width types.
Learn iterative and recursive ways to print the Fibonacci sequence.
8 people found this page helpful