- Expand
5·4·3·2·1
Find Factorial in C
What you’ll learn
- The definition of
n!forn ≥ 0, including0! = 1. - A recursive solution matching the classic interview style, plus an iterative equivalent.
- Overflow limits for
unsigned long long, input validation, and a small live preview.
Overview
Factorial grows faster than any exponential. A correct small-n program is easy; a robust one also checks n ≥ 0, watches overflow, and picks recursion or a loop based on constraints.
Two programs
Recursive (5! = 120) and iterative with the same result.
Live preview
Exact integers for 0 ≤ n ≤ 20 in this widget (fits unsigned long long and JS safe integers).
Rigor
Guards for negative inputs and 21+ overflow on 64-bit unsigned long long.
Prerequisites
Functions, if, multiplication, and optional for loops.
#include <stdio.h>,int main(void),printfwith%llufor wide unsigned results.- Awareness that fixed-width integers wrap on overflow in C unsigned arithmetic.
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, so 0! = 1.
Factorials count permutations: n! is the number of ways to order n distinct objects. They appear in Taylor series, binomial coefficients, and probability.
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 (matches a typical unsigned long long ceiling before wrap).
Algorithm
Goal: compute n! for nonnegative n within a chosen numeric type.
Base case
If n ≤ 1, return 1 (covers 0! and 1!).
Recurrence or loop
Otherwise multiply n by (n-1)!, or initialize result = 1 and absorb factors 2..n in a loop.
📜 Pseudocode
function factorial(n): // assume n >= 0
if n <= 1:
return 1
return n * factorial(n - 1) Recursive factorial
Same idea as the reference (calculateFactorial there): recursion, number = 5, and %llu output. Renamed to calculate_factorial here, with a safe upper bound for unsigned long long on 64-bit targets.
#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;
} Explanation
Each call shrinks num until the base case; the products bubble back up. Cast num before multiplying so intermediate products stay in unsigned long long.
Iterative factorial
Same numeric result for n = 5, with O(1) auxiliary space and no call-stack depth proportional 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;
} Explanation
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.
Optimization and scaling
Bigger values. Use arbitrary-precision libraries (GMP), logarithms of gamma for floating approximations, or prime-factor exponent tables for exact huge factorials—not a widening long long alone.
Prime swing / split recursion. Advanced algorithms reduce the number of large multiplications; overkill for basic interviews.
Interview: state overflow, validate n ≥ 0, and compare recursion depth vs loop.
❓ FAQ
🔄 Input / output examples
Change number in either example (within 0..20 for exact unsigned long long here).
| n | n! |
|---|---|
0 | 1 |
1 | 1 |
5 | 120 |
20 | 2432902008176640000 |
Edge cases and pitfalls
Unsigned overflow is silent in C; always bound n or check products against limits before they wrap.
n < 0
Not the standard factorial; reject or map to an error code instead of recursing.
21! and beyond
Exceeds 2^64-1; widen to big integers or reduce the problem (e.g. trailing zeros modulo).
Deep recursion
Even when n fits in a type, very large n can overflow the call stack before the integer does.
int result
13! already exceeds 32-bit int; prefer wide unsigned for small-n exact factorials.
⏱️ 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!; only the hidden stack differs.
Summary
- Definition:
0! = 1andn! = n·(n-1)!forn ≥ 1. - Code: recursion matches the classic template; iteration saves stack depth.
- Watch-outs: negatives undefined,
unsigned long longcaps near20!, silent unsigned wrap.
Stirling'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.
8 people found this page helpful
