Loop Assignment 26 — Sum of Series 1! + 2! + 3! + … + N! Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Sum of the Series 1! + 2! + 3! + … + N! Using a For Loop

📑 On this page:
  • The Running-Factorial Trick
  • The Algorithm in Four Lines
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why recomputing i! from scratch is wasteful, and how a running factorial fixes it
  • How a single fact *= i turns an O(N²) program into an O(N) one
  • Why int overflows at 13! and why long long is 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.

Diagram showing running factorial: fact = 1, 2, 6, 24, 120, 720 while i = 1, 2, 3, 4, 5, 6 and sum accumulates 1, 3, 9, 33, 153, 873

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
111Trivial
3691 + 2 + 6
5120153Fits in int
103,628,8004,037,913Still fits in 32-bit int
12479,001,600522,956,313Last N that fits in signed 32-bit int
136,227,020,8006,749,977,113Overflows 32-bit int — needs long long
202,432,902,008,176,640,0002,561,327,482,637,313,013Largest 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:

  1. i = 1: fact = 1 × 1 = 1, sum = 0 + 1 = 1
  2. i = 2: fact = 1 × 2 = 2, sum = 1 + 2 = 3
  3. i = 3: fact = 2 × 3 = 6, sum = 3 + 6 = 9
  4. i = 4: fact = 6 × 4 = 24, sum = 9 + 24 = 33
  5. i = 5: fact = 24 × 5 = 120, sum = 33 + 120 = 153
  6. i = 6: condition i <= 5 is 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.

📖 Related Tutorials

  • 25. Sum of the Series 1 + 1/2² + 1/3² + … + 1/N² Using a For Loop
  • 27. Generate the First N Terms of the Tribonacci Sequence Using a While Loop
  • 28. Find the Largest Prime Factor Using a While Loop
  • 29. Iterative Binary Search Using a While Loop
  • 30. Check Amicable Numbers Using a For Loop
  • C FOR Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 25. Sum of the Series 1 + 1/2² + 1/3² + … + 1/N² Using a For Loop   ||   Next Topic: -->> 27. Generate the First N Terms of the Tribonacci Sequence Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.