Find the Sum of the Series: 1/1! + 1/2! + 1/3! + … + 1/n! using JavaScript ?
Last Updated :
17 Apr, 2024
We are going to discuss how we can find the sum of series: 1/1! + 1/2! + 1/3! + …… till n terms.
Below are the approaches to find the sum of series:
Using for loop
We will first define a function to calculate factorial of a given number. It checks if the number is 0 or 1 it returns 1 else, it recursively calculates factorial. Now we define another function and initialize a variable sum to 0. Use a for loop to iterate from 1 to n. For each iteration, calculate the reciprocal of the factorial of the current number i and add it to the sum. Return sum.
Example: To demonstrate calculation of sum of given series using for loop
JavaScript
// Using for loop
function factorial(num) {
if (num === 0 || num === 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
function sumSeries(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += 1 / factorial(i);
}
return sum;
}
console.log(sumSeries(3));
Time Complexity: O(n)
Space Complexity: O(n)
Using Recursion
We will first define a function to calculate factorial of a given number. It checks if the number is 0 or 1 it returns 1 else, it recursively calculates factorial. We will create another recursive function. The base case of this recursive function is : If n is 1, return 1. Else, calculate the reciprocal of the factorial of n and add it to the result of recursively calling the function with n – 1.
Example: To demonstrate calculation of sum of given series using recursion.
JavaScript
// Using recursion
function factorial(num) {
if (num === 0 || num === 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
function sumSeries(n) {
if (n === 1) {
return 1;
}
return 1 / factorial(n) + sumSeries(n - 1);
}
console.log(sumSeries(3));
Time Complexity: O(n)
Space Complexity: O(n)
Share your thoughts in the comments
Please Login to comment...