Find sum of the series 1-2+3-4+5-6+7....in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer value N. Our task is to find Sum of Series 1 - 2 + 3 - 4 + 5 - 6 + 7 upto n terms.

The series is 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 - 10...

Let's take an example to understand the problem,

Input : N = 4
Output : -2

Explanation

1 - 2 + 3 - 4 = -2

Solution Approach

A simple approach to solve the problem is finding the general term of the series and then finding the sum till n terms. And calculating the sum using formula will reduce the time to O(1).

The series is,

1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 - 10...

Let's find the sum of series for some values,

sum(1) = 1

sum(2) = 1 - 2 = -1

sum(3) = 1 - 2 + 3 = 2

sum(4) = 1 - 2 + 3 - 4 = -2

sum(5) = 1 - 2 + 3 - 4 + 5 = 3

sum(6) = 1 - 2 + 3 - 4 + 5 - 6 = -3

sum(7) = 1 - 2 + 3 - 4 + 5 - 6 + 7 = 4

sum(8) = 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 = -4

For here, we can conclude that the sum can be formulated as,

Sum = +(n+1)/2 if n is odd.

Sum = -(n)/2 if n is even.

Example

Program to illustrate the working of our solution

#include<iostream>
using namespace std;
int calcSumNTerms(int n) {
   if(n%2 == 0)
      return ((-1)*(n/2));
   return ((n+1)/2);
}
int main() {
   int n = 156;
   cout<<"The sum of series upto n terms is "<<calcSumNTerms(n); 
   return 0;
}

Output

The sum of series upto n terms is -78
raja
Updated on 27-Jan-2022 08:45:24

Advertisements