Tutorialspoint
Problem
Solution
Submissions

Sum of the Series 1! + 2! + ... + n!

Certification: Basic Level Accuracy: 100% Submissions: 4 Points: 10

Write a C++ program to calculate the sum of the series 1! + 2! + 3! + ... + n!, where n! represents the factorial of n.

Example 1
  • Input: n = 5
  • Output: 153
  • Explanation:
    • Step 1: Calculate the factorials for each number from 1 to 5.
    • Step 2: 1! = 1, 2! = 2, 3! = 6, 4! = 24, 5! = 120.
    • Step 3: Sum = 1! + 2! + 3! + 4! + 5! = 1 + 2 + 6 + 24 + 120 = 153.
Example 2
  • Input: n = 3
  • Output: 9
  • Explanation:
    • Step 1: Calculate the factorials for each number from 1 to 3.
    • Step 2: 1! = 1, 2! = 2, 3! = 6.
    • Step 3: Sum = 1! + 2! + 3! = 1 + 2 + 6 = 9.
Constraints
  • 1 ≤ n ≤ 20
  • Time Complexity: O(n), where n is the input number
  • Space Complexity: O(1)
  • The result may be large, so use long long int for calculations
NumberControl StructuresTCS (Tata Consultancy Services)Airbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Calculate the factorial of each number from 1 to n.
  • Keep a running sum of factorials.
  • Be careful about integer overflow for larger values of n.
  • You can optimize by calculating each factorial based on the previous one instead of recalculating from scratch.

Steps to solve by this approach:

 Step 1: Define a function sumOfFactorialSeries that takes an integer n.

 Step 2: Initialize a sum variable to 0 and a factorial variable to 1.
 Step 3: Use a for loop from i=1 to i=n.
 Step 4: For each iteration, update the factorial by multiplying it by i.
 Step 5: Add the current factorial to the sum.
 Step 6: Return the final sum.

Submitted Code :