Open In App

Sum of the Series: 1 + 1/2 + 1/3 + … + 1/n using JavaScript

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:

Using for loop

We 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.

// using for loop

function seriesSumForLoop(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += 1 / i;
    }
    return sum;
}

// Number of terms 
const n = 7;
const result = seriesSumForLoop(n);
console.log(`Sum of the series using
             for loop is :`, result);

Output
Sum of the series using
             for loop is : 2.5928571428571425

Time complexity: O(n)

Space complexity: O(1)

Using Recursion

We 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.

// using recursion

function seriesSumRecursion(n) {
    // Base case
    if (n === 1) {
        return 1;
    }
    // Recursive case
    return 1 / n + seriesSumRecursion(n - 1);
}

// Number of terms 
const n = 7; 
const result = seriesSumRecursion(n);
console.log(`Sum of the series using 
             recursion is :`, result);

Output
Sum of the series using 
             recursion is : 2.5928571428571425

Time complexity: O(n)

Space complexity: O(n)

Article Tags :