- Why recomputing
i!from scratch is wasteful, and how a running factorial fixes it - How a single
fact *= iturns an O(N²) program into an O(N) one - Why
intoverflows at 13! and whylong longis needed - Why the sum overflow is even worse than the factorial overflow
- How this series relates to the mathematical constant e
The Running-Factorial Trick
The naive way to compute 1! + 2! + 3! + … + N! is to compute each factorial from scratch. For each i, you run an inner loop that multiplies 1 × 2 × … × i. That's a nested loop, and it does about N²/2 multiplications — 50 for N = 10, 5000 for N = 100, 500,000 for N = 1000. For N = 20 (the largest N that fits in long long), the inner loop would total 210 multiplications just to compute the factorials, plus the additions. Wasteful but not disastrous at that scale.
The smarter way is to notice that 5! = 4! × 5. If you already have 4! from the previous iteration, you get 5! with a single multiplication. That's the running factorial: keep fact alive across iterations and multiply it by i each time. No inner loop, no wasted multiplications. The whole program becomes a single for loop with two accumulators — one for the factorial and one for the sum.
This is the same pattern as the running-sum and running-product loops you've already seen. The difference is that here you have two accumulators updated in the same loop body: fact and sum. Each iteration does O(1) work, so the whole program is O(N) — the same complexity as the simple sum loop, but computing something much more interesting.
💡 In one line: fact *= i carries the previous factorial forward — no inner loop needed — and sum += fact adds each term as it's computed.
The Algorithm in Four Lines
In pseudocode, the running-factorial version is only slightly longer than the trivial series:
fact = 1
sum = 0
for i = 1 to N:
fact = fact * i
sum = sum + fact
print sum
Two variables updated in lockstep. The factorial grows fast, so the sum grows even faster (roughly as N! for the last term). By N = 20, the sum is over 2.5 quintillion — the last few digits of a 64-bit integer.
| N | N! | Sum 1!+…+N! | Notes |
|---|---|---|---|
| 1 | 1 | 1 | Trivial |
| 3 | 6 | 9 | 1 + 2 + 6 |
| 5 | 120 | 153 | Fits in int |
| 10 | 3,628,800 | 4,037,913 | Still fits in 32-bit int |
| 12 | 479,001,600 | 522,956,313 | Last N that fits in signed 32-bit int |
| 13 | 6,227,020,800 | 6,749,977,113 | Overflows 32-bit int — needs long long |
| 20 | 2,432,902,008,176,640,000 | 2,561,327,482,637,313,013 | Largest N that fits in long long |
The jump from 12 to 13 is the classic 32-bit int overflow boundary. After that, the numbers grow so fast that even long long only survives up to N = 20 before overflowing. Beyond that, you'd need unsigned long long (up to about N = 22), then __int128 (up to about N = 34), then arbitrary-precision arithmetic.
Complete C Program
Program: sum of factorials using a for loop
#include <stdio.h>
int main(void) {
int n;
printf("Enter the number of terms (N): ");
if (scanf("%d", &n) != 1 || n < 1) {
printf("Invalid input. Enter a positive integer.\n");
return 1;
}
unsigned long long fact = 1;
unsigned long long sum = 0;
for (int i = 1; i <= n; i++) {
fact *= i; /* running factorial: 1, 1, 2, 6, 24, ... */
sum += fact; /* add this term to the running total */
}
printf("Sum of the series 1! + 2! + ... + %d! = %llu\n", n, sum);
return 0;
}
Note the unsigned long long type. For N up to about 20, long long (signed) works. For N up to 22, unsigned long long works. Beyond that, you need a bignum library. The assignment's typical input range is N ≤ 10, so either type is fine — but unsigned long long is the safest choice for a general-purpose program.
And here's the naive nested-loop version, for comparison. Don't use this in production, but it's useful to see why the running factorial is better:
Antipattern: recomputing each factorial from scratch (O(N²))
/* DON'T write this in real code — it's O(N^2) when O(N) is possible */
unsigned long long sum = 0;
for (int i = 1; i <= n; i++) {
unsigned long long term = 1;
for (int j = 1; j <= i; j++)
term *= j;
sum += term;
}
The inner loop recomputes 1 · 2 · … · i for each i. Total multiplications ≈ N²/2. For N = 20 it's 210 multiplications instead of 20.
Program Output
Enter the number of terms (N): 5
Sum of the series 1! + 2! + ... + 5! = 153
Try a few more. Input 3 and you should get 9 (1 + 2 + 6). Input 10 and you should get 4037913. Input 12 and you should get 522956313. Input 13 and the sum is 6749977113 — which is why int gives the wrong answer (negative, in fact, because of the sign bit) while unsigned long long gives the correct value.
Step-by-Step Explanation
Let's walk through N = 5 and see the two accumulators evolve together.
1. Reading and validating input
scanf("%d", &n) reads an integer. The check != 1 || n < 1 handles both garbage input and zero or negative N. The series starts at 1!, so N must be at least 1. There's no upper bound enforced in the code, but in practice the sum overflows for N > 20, so you'd want to add a check like if (n > 20) { warning } in production code.
2. The two accumulators
fact = 1 and sum = 0. Both are unsigned long long so they hold up to 2⁶⁴ − 1 ≈ 1.8 × 10¹⁹. That's enough for N up to 20 (20! ≈ 2.4 × 10¹⁸) and N up to 21 (21! ≈ 5.1 × 10¹⁹ — actually that overflows unsigned long long too, so really N ≤ 20). The starting value of fact = 1 is essential — it's the multiplicative identity, so fact * i for the first iteration gives exactly i.
3. The loop, iteration by iteration
For N = 5:
i = 1:fact = 1 × 1 = 1,sum = 0 + 1 = 1i = 2:fact = 1 × 2 = 2,sum = 1 + 2 = 3i = 3:fact = 2 × 3 = 6,sum = 3 + 6 = 9i = 4:fact = 6 × 4 = 24,sum = 9 + 24 = 33i = 5:fact = 24 × 5 = 120,sum = 33 + 120 = 153i = 6: conditioni <= 5is false — loop exits
Final sum = 153. Notice that fact and sum both grow monotonically. The running factorial is the dominant cost — the sum is roughly N! × (1 + 1/N + 1/(N(N−1)) + …), which is close to N! but slightly larger. For N = 5, sum = 153 and 5! = 120, so the sum is about 1.28× the last term.
4. Why the loop is O(N)
Each iteration does exactly two multiplications and one addition — constant work. The loop runs N times. Total work: O(N). The naive nested-loop version does 1 + 2 + … + N = N(N+1)/2 multiplications, which is O(N²). For N = 20, that's 210 vs 20 — a factor of 10. For N = 200, it's 20,100 vs 200 — a factor of 100. The gap widens with N, which is exactly why the running-factorial trick matters.
5. The overflow boundary
A 32-bit signed int holds up to 2,147,483,647. 12! = 479,001,600 fits, but 13! = 6,227,020,800 doesn't. So the first overflow happens when N reaches 13. A 64-bit long long holds up to about 9.2 × 10¹⁸, which covers 20! (2.4 × 10¹⁸) but not 21! (5.1 × 10¹⁹). So long long (signed) handles N ≤ 20; unsigned long long handles N ≤ 20 too (its maximum is 1.8 × 10¹⁹, just under 21! = 5.1 × 10¹⁹ — so actually also N ≤ 20). For larger N, use a bignum library or Python.
6. The connection to the constant e
If you divide the partial sums by N!, you get a sequence that approaches the mathematical constant e ≈ 2.71828. Specifically, (1! + 2! + … + N!) / N! → e as N → ∞. This is a beautiful identity, but it's not what this assignment asks for — the assignment just wants the sum. Still, it's worth knowing that this series appears in probability theory (where it counts permutations) and in the analysis of algorithms (where N! terms in a recurrence suggest an O(N!) algorithm, and the sum over k of k! can appear as an upper bound).
🎯 Remember this: carry fact forward with fact *= i. Use long long (or unsigned long long) — int overflows at 13!. The loop is O(N) because each term takes constant work. And the sum grows roughly like N!, so N is bounded by the integer type you choose.
Frequently Asked Questions
1. Why does my program produce a negative number for N = 13?
You're using int for the sum or factorial, and 13! = 6,227,020,800 exceeds INT_MAX = 2,147,483,647. Signed integer overflow in C is undefined behavior, but on most compilers it wraps around to a negative value. Switch to long long (signed) or unsigned long long and it works up to N = 20.
2. Can I compute each factorial with a separate inner loop?
Yes, but it's O(N²) instead of O(N). The running-factorial trick (fact *= i) carries the previous factorial forward with a single multiplication per iteration. For small N the difference is imperceptible, but as a habit, the O(N) version is the one to write.
3. What is the largest N this program can handle?
With unsigned long long, N = 20 is the maximum — 20! = 2,432,902,008,176,640,000 fits in 64 bits, but 21! overflows. For larger N, you'd need __int128 (GCC/Clang extension) up to about N = 34, or a bignum library for anything beyond that.
4. Why start fact at 1 instead of 0?
Because 1 is the multiplicative identity. If fact starts at 0, then fact *= i is always 0 — the whole product collapses. The initial value of a multiplicative accumulator must be 1, not 0. For the sum, the initial value is 0 (the additive identity) — that's why sum = 0 and fact = 1.
5. What's the connection between this series and e?
If you divide the sum by N!, you get 1 + 1/2 + 1/6 + … + 1/(N·(N−1)·…·2), which approaches e ≈ 2.71828 as N grows. It's a nice mathematical fact, but not what the assignment asks for. The sum itself is roughly N! × (some constant between 1 and 2) for large N.
6. Can I use recursion instead of a loop?
Yes — a recursive factorial(n) and a recursive sum_series(n) both work. But recursion is overkill for this problem and risks stack overflow for large N (though N ≤ 20 here, so it's safe). The loop version is simpler and faster, and it's the expected solution for a "for loop assignment".
💡 Tip: After this program, try the alternating series 1! − 2! + 3! − 4! + … — it converges to a much smaller number (around 0.56 for large N) and the sign alternation is a useful exercise in toggling signs. Then try the reciprocal series 1/1! + 1/2! + 1/3! + … — it converges to e − 1 ≈ 1.71828, and the terms shrink so fast that N = 10 is already accurate to 7 decimal places.