Sum of series 2/3 – 4/5 + 6/7 – 8/9 + …… upto n terms

CServer Side ProgrammingProgramming

A series is a sequence of numbers that have some common traits that each number follows. There are various series defined in mathematics with sum mathematical logic or mathematical formula. In this problem we are given a series of numbers 2/3 , -4/5 , 6/7 , -8/9 , …..

The general term of the series can be defined as (-1)n *(2*n)/ ((2*n)+1)

To find the sum of series, we need to add each element of the given series as, 2/3 - 4/5 + 6/7 - 8/9 + ……

Let's take an example,

Input: 10
Output: -0.191921

Explanation

(2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11) - (12 / 13) + (14 / 15) - (16 / 17) + (18 / 19) - (20 / 21) = -0.191921


Input: 17
Output: 0.77152

Explanation

(2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11) - (12 / 13) + (14 / 15) - (16 / 17) + (18 / 19) - (20 / 21) = 0.77152

Example

#include <iostream>
using namespace std;
int main() {
   int n = 17,i = 1;
   double res = 0.0;
   bool sign = true;
   while (n > 0) {
      n--;
      if (sign) {
         sign = !sign;
         res = res + (double)++i / ++i;
      } else {
         sign = !sign;
         res = res - (double)++i / ++i;
      }
   }
   cout << "The sum of the given series is "<< res;
   return 0;
}

Output

The sum of given series is 0.77152
raja
Published on 19-Aug-2019 12:00:52
Advertisements