Numbers · beginner
C Program to Find the Factorial of a Number
Find the factorial of a number in C with a loop and with recursion, use unsigned long long to reach 20!, and detect overflow before it gives wrong answers.
- for loop
- recursion
- unsigned long long
- integer overflow
The factorial n! is the product 1 × 2 × … × n, with 0! = 1. Factorials grow very fast: 13! already exceeds a 32-bit int, and 20! is the largest that fits in a 64-bit unsigned long long. Past that, C integers wrap around without any error, so a careful program checks before multiplying.
The program
#include <stdio.h>
unsigned long long factorial(int n) {
unsigned long long result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
int main(void) {
printf("5! = %llu\n", factorial(5));
printf("0! = %llu\n", factorial(0));
printf("20! = %llu\n", factorial(20));
return 0;
}5! = 120
0! = 1
20! = 2432902008176640000How it works
- result starts at 1, which is also the answer for 0 and 1 because the loop does not run for them.
- result *= i multiplies in 2, 3, … up to n.
- unsigned long long holds values up to about 1.8 × 10¹⁹, enough for 20!.
- %llu is the printf format for unsigned long long.
Another way: Recursion, with an overflow check
The recursive version follows n! = n × (n - 1)!. Before multiplying it checks whether the result would exceed ULLONG_MAX (from limits.h); 21! would.
#include <limits.h>
#include <stdio.h>
int factorial(int n, unsigned long long *out) {
if (n <= 1) {
*out = 1;
return 1;
}
unsigned long long smaller;
if (!factorial(n - 1, &smaller) || smaller > ULLONG_MAX / n)
return 0;
*out = smaller * n;
return 1;
}
int main(void) {
unsigned long long value;
for (int n = 19; n <= 21; n++) {
if (factorial(n, &value))
printf("%d! = %llu\n", n, value);
else
printf("%d! is too large for unsigned long long\n", n);
}
return 0;
}19! = 121645100408832000
20! = 2432902008176640000
21! is too large for unsigned long longCommon mistakes
- Using int: 13! = 6,227,020,800 does not fit, and the printed result is silently wrong.
- Printing unsigned long long with %d instead of %llu, which prints garbage.
- Starting result at 0, which makes every factorial 0.
- A recursive factorial without a base case recurses until the stack overflows.
Try it yourself
- Print a table of n! for n from 0 to 20.
- Count the trailing zeros of 100! without computing it (count the factors of 5).
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.