![]() |
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: Table of Content Using for loopIn 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
Output 2.1332555301595546 Time Complexity: O(n) Space Complexity: O(1) Using while loopIn 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
Output 2.1332555301595546 Time Complexity: O(n) Space Complexity: O(1) Using RecursionIn 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.
Output Sum of the series till 5 terms is 1.7873015873015872 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |