![]() |
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: Table of Content Using for loopWe 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
Output 1.6666666666666667 Time Complexity: O(n) Space Complexity: O(n) Using RecursionWe 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.
Output 1.6666666666666667 Time Complexity: O(n) Space Complexity: O(n) Using Memoization for Factorial CalculationIn this approach, we use memoization to store previously calculated factorials to optimize the calculation of the sum of the series. This reduces the number of redundant calculations and improves the efficiency of the program. Example: This JavaScript code demonstrates how to calculate the sum of the series using memoization for factorial calculation.
Output Sum of the series till 5 terms is 1.7166666666666668 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |