Factorialn! = n * (n-1)! with 0! = 1 is a clean linear recursion. FibonacciF(n) = F(n-1) + F(n-2) with F(0) = 0, F(1) = 1 branches twice per call, so the naive version recomputes values and takes exponential time. An iterative loop (or memoization) removes the repeated work.
Remember
unsigned long long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
Reference
Cheat Sheet
Keep these facts handy while you work with Factorial and Fibonacci in C.
Topic
Detail
Factorial
O(n) calls
Naive Fibonacci
Exponential calls
Iterative Fibonacci
O(n) time, O(1) space
Overflow
21! overflows 64 bits
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Tower of Hanoi.
Example 1 — Factorial and Fibonacci with call counts
Compare recursive and iterative Fibonacci for n = 10.
C
#include <stdio.h>
static long calls;
static unsigned long long fact(int n) {
return n <= 1 ? 1 : (unsigned long long)n * fact(n - 1);
}
static int fib(int n) {
calls++;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
int main(void) {
printf("10! = %llu\n", fact(10));
int f = fib(10);
printf("fib(10) = %d (naive calls: %ld)\n", f, calls);
int a = 0, b = 1;
for (int i = 0; i < 10; i++) { int t = a + b; a = b; b = t; }
printf("fib(10) iterative = %d\n", a);
return 0;
}
Naive fib(10) makes 177 calls because subproblems like fib(5) are recomputed many times.
The loop gets the same answer with ten additions.
Edge Cases & Pitfalls
Check these before relying on Factorial and Fibonacci in real programs.
exp
Exponential Fibonacci
fib(40) makes over 300 million calls. Memoize or iterate.
of
Factorial overflow
int overflows at 13!. Even unsigned long long overflows at 21!.
Remember
Key Takeaways
Factorial: linear recursion.
Fibonacci: branching recursion.
Repeated work makes naive Fibonacci slow.
One line: Factorial n! = n * (n-1)! with 0! = 1 is a clean linear recursion.
Frequently Asked Questions
It recomputes the same subproblems repeatedly, so the number of calls grows exponentially.
Use iteration, or memoization (cache results), to compute each value once.
Continue with "C Tower of Hanoi" next. Solve Tower of Hanoi recursively and list every move. The C Recursion and Backtracking hub lists every topic in order.