Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number n of the series. Our task is to find the sum of series 1^2 + 3^2 + 5^2 +... + (2*n - 1)^2 for the given value of n.

Let’s take an example to understand the problem,

Input

n = 5

Output

84

Explanation

sum = 1^2 + 3^2 + 5^2 + 7^2 + 9^2
= 1 + 9 + 25 + 49 = 84

A basic approach to solve this problem is by directly applying the formula for the sum of series.

Example

 Live Demo

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

Output

The sum of series up to 10 is 165

Another approach to solve is to use the mathematical formula to find the sum of the series.

The sum is,

1^2 + 3^2 + 5^2 + … + (2*n - 1)^2 =
{(n * (2*(n-1)) * (2*(n+1)))/3}

Example

 Live Demo

#include <iostream>
using namespace std;
int calcSumOfSeries(int n) {
   return (n * (2 * n - 1) * (2 * n + 1)) / 3;
}
int main() {
   int n = 5;
   cout<<"The sum of series up to "<<n<<" is "<<calcSumOfSeries(n);
   return 0;
}

Output

The sum of series up to 5 is 165
raja
Published on 05-Aug-2020 08:14:26
Advertisements