Find Sum of Series 1^2 - 2^2 + 3^2 - 4^2 ... upto n terms in C++


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

Let's take an example to understand the problem,

Input : N = 3
Output : 6

Explanation

12 - 22 + 32 = 1 - 4 + 9 = 6

Solution Approach

A simple approach to solve the problem is using loops. We will loop from 1 to n with iterator i.

If i is odd, add (i2) to the sum.

If i is even, subtract (i2) to the sum. At last, return the sum of series after the loop.

Algorithm

Initialise − sum = 0.

  • Step 1 −Loop till n, i -> 1 to n

    • Step 1.1 − if i is odd, add (i2) to sum, if (i % 2 == 0) => sum += i2

    • Step 1.2 − if i is even, add (i2) to sum, if (i % 2 == 0) => sum -= i2

  • Step 2 − Return sum.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findSumOfSeries(int n) {
   int sum = 0;
   for (int i = 1; i <= n; i++) {
      if (i % 2 == 0)
         sum -= (i*i);
      else
         sum += (i*i);
   }
   return sum;
}
int main(void) {
   int n = 5;
   cout<<"The sum of series is "<<findSumOfSeries(n);
}

Output

The sum of series is 15

Another approach is using formulas for the sum of series.

If N is even,

$\mathrm{sum\:=\:1^2\:-\:2^2\:+\:3^2\:-\:4^2\:+\:\dotsm\:+\:(n-1)^2\:-n^2}$

$\mathrm{sum\:=\:(1-2)(1+2)\:+\:(3-4)(3+4)\:+\:\dotsm(n-1-n)(n-1+n)}$

$\mathrm{sum\:=\:(-1)(3)\:+\:(-1)(7)\:+\:(-1)(2n-1)}$

$\mathrm{sum\:=\:(-1)(1+2+3+4+\dotsm\:+(n-1)+n)}$

$\mathrm{sum\:=\:(-1)\:*\:\begin{bmatrix}\frac{n*(n+1)}{2} \end{bmatrix}}$

If N is odd,

$\mathrm{sum\:=\:1^2\:-\:2^2\:+\:3^2\:-\:4^2\:+\:\dotsm\:+\:(n-2)^2\:-(n-1)^2\:+\:n^2}$

$\mathrm{sum\:=\:(1^2\:-\:2^2\:+\:3^2\:-\:4^2\:+\:\dotsm\:+\:(n-2)^2\:-(n-1)^2)\:+\:n^2}$

$\mathrm{sum\:=\:\lbrace(-1)\:*[\frac{n*(n+1)}{2}]\rbrace\:+\:n^2}$

$\mathrm{sum\:=\:(\frac{-n^2\:+\:n\:+\:2n^2}{2})}$

$\mathrm{sum\:=\:(n+n^2)/2\:=\:n^*(n+1)/2}$

Example

Program to illustrate the working of our solution

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

Output

The sum of series is 15

Updated on: 27-Jan-2022

626 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements