Horje
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 examples.

Below are approaches to calculate the 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

JavaScript
// 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

JavaScript
// 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)

Using Recursion

In this approach, we use recursion to calculate the sum of the series. The base case for the recursion is when n is 1, and for the recursive case, we add 1 / (2 * n – 1) to the sum of the series for n – 1 terms.

Example: To demonstrate calculation of sum of the given series using recursion.

JavaScript
// Function to calculate the sum of the series using recursion
function sumSeries(n) {
    if (n === 1) {
        return 1;
    } else {
        return 1 / (2 * n - 1) + sumSeries(n - 1);
    }
}

const n = 5;
const result = sumSeries(n);
console.log(`Sum of the series till ${n} terms is ${result}`);

Output
Sum of the series till 5 terms is 1.7873015873015872



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JSON Interview Questions JSON Interview Questions
How to Remove HTML Tags from a String in JavaScript? How to Remove HTML Tags from a String in JavaScript?
JavaScript program to find volume of cylinder JavaScript program to find volume of cylinder
How to Change Button Label in Alert Box using JavaScript ? How to Change Button Label in Alert Box using JavaScript ?
How to work with Structs in JavaScript ? How to work with Structs in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14