Find sum of factorials till N factorial (1! + 2! + 3! + … + N!)
Given a positive integer N. The task is to compute the sum of factorial from 1! to N!, 1! + 2! + 3! + … + N!.
Input: N = 5
Explanation: 1! + 2! + 3! + 4! + 5! = 1 + 2 + 6 + 24 + 120 = 153.
Input: N = 1
Naive Approach: The basic way to solve this problem is to find the factorial of all numbers till 1 to N and calculate their sum.
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Approach: An efficient approach is to calculate factorial and sum in the same loop making the time O(N). Traverse the numbers from 1 to N and for each number i:
- Multiply i with previous factorial (initially 1).
- Add this new factorial to a collective sum
At the end, print this collective sum.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(1), since no extra space has been taken.