![]() |
We are going to learn how we can find the sum of series: 1/1 + 1/2 + 1/3 + …… till n terms using JavaScript. Below are approaches to calculate sum of the series: Table of Content Using for loopWe will create a function and Initialize a variable named sum (set it 0 initially) to store the sum of the series. Use a for loop to iterate from 1 to n and in each iteration, add 1 / i to the sum. After the loop finishes, return the calculated sum. Example: To demonstrate calculation of sum of given series using for loop.
Output Sum of the series using for loop is : 2.5928571428571425 Time complexity: O(n) Space complexity: O(1) Using RecursionWe will create a recursive function. The base case for this recursive function is, if value of n is 1 then it returns 1 , else in the recursive case, it calculates 1/n and adds it to the sum of the series for n-1 terms, which is obtained by recursively calling the function. The recursion continues until the base case is reached. Example: To demonstrate calculation of given series using recursion.
Output Sum of the series using recursion is : 2.5928571428571425 Time complexity: O(n) Space complexity: O(n) Using Array.reduce() MethodIn this approach, we can use the Array.reduce() method to calculate the sum of the series. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. Example: This JavaScript code demonstrates how to calculate the sum of the series using the reduce() method.
Output Sum of the series till 5 terms is 2.283333333333333 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |