![]() |
One can find the sum of n terms of Harmonic Progression using JavaScript. Harmonic Progression is a sequence of real numbers in which each term is reciprocal of Arithmetic Progression. There are different approaches to finding the sum of n terms of Harmonic Progression which are discussed below: Table of Content Using IterationIn this approach, we will create a function and initialize a variable sum to store the sum of Harmonic Progression. We will use a loop to iterate from 1 to n and in each iteration we will add the reciprocal of the current sum i.e. (we will add 1/i) to the sum. After the loop finishes , we will return the result stored in sum variable. Example: To demonstrate finding sum of first n terms in the H.P. series using iterative function which uses loop to traverse every element until number of terms reaches to print the result.
Output The sum of the first 7 terms of the H.P. is: 2.5928571428571425
Space Complexity : O(1) , constant space Using RecursionIn this approach we will define a recursive function. This function stops( i.e. base case) when n is 1 , it will return 1. If n is greater than 1, recursively call the function to calculate the sum of the current term (1/n) and the sum of the previous terms (recursive call with n – 1). Return the result after recursive call stops. Example: To demonstrate finding sum of first n terms in the G.P. series using recursive function which uses recursive calls till base case reaches to print the result.
Output The sum of the first 7 terms of the H.P. is:2.5928571428571425 Time Complexity : O(n) , as function make recursive call n times. Space Complexity : O(n) , n recursive calls are made. Using Direct FormulaThe Sum of first n terms in H.P. is calculated by using the formula for sum of first n terms of H.P. described below : Syntax:Sn = (n/a) + ((n * (n - 1) / 2) * (1 / d)) where:
Example : To demonstrate finding sum of first n terms in the H.P. series using the function which uses sum of first n terms formula to calculate sum of first n terms of an H.P. series to print the result.
Output Sum of first 7 terms of harmonic progression: 12.833333333333334 Time Complexity : O(1) , constant time Space Complexity : O(1) , constant space |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |