Open In App

Find the Sum of the Series: 1 + 1/3 + 1/5 + … + 1/(2n-1) using JavaScript ?

We are going to discuss how we can find the sum of series : 1 + 1/3 + 1/5 + ... ...till n terms. we will discuss some approaches with example.

Below are approaches to calculate sum of the series:

Using for loop

In this approach, we are 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 /(2 * i - 1) 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 sumOfSeries(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += 1 / (2 * i - 1);
    }
    return sum;
}

console.log(sumOfSeries(10)); 

Output
2.1332555301595546

Time Complexity: O(n)

Space Complexity: O(1)

Using while loop

In this approach, we are using while loop. We will create a function and Initialize a variable named sum (set it 0 initially) to store the sum of the series and initialize another variable i with value 1. W will use a while loop to iterate until i is less than or equal to n. Inside the loop add 1 / (2 * i - 1) to sum, and increment i by 1 in each iteration. Return the calculated sum.

Example: To demonstrate calculation of sum of given series using while loop

// Using while loop

function sumOfSeries(n) {
    let sum = 0;
    let i = 1;
    while (i <= n) {
        sum += 1 / (2 * i - 1);
        i++;
    }
    return sum;
}

console.log(sumOfSeries(10)); 

Output
2.1332555301595546

Time Complexity: O(n)

Space Complexity: O(1)

Article Tags :