
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of the Series 2 + 2 + 4 + 2 + 4 + 6 + 2 + 4 + 6 + 8 + ... + 2n in C++
In this problem, we are given a number n which defines the nth term of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n). Our task is to create a program to find the sum of the series.
Let’s take an example to understand the problem,
Input
n = 3
Output
Explanation − sum = (2) + (2+4) + (2+4+6) = 2 + 6 + 12 = 20
A simple solution to the problem is to use a nested loop. The inner loop finds the ith element of the series and then add up all elements to the sum variable.
Example
Program to illustrate the working of our solution,
#include <iostream> using namespace std; int calcSeriesSum(int n) { int sum = 0; for (int i = 1; i<=n; i++) { int even = 2; for (int j = 1; j<=i; j++) { sum += even; even += 2; } } return sum; } int main() { int n = 5; cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n); return 0; }
Output
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70
This is not the most effective way to solve the problem as the time complexity of the problem is of the order O(n2).
An effective solution to the problem is by using the mathematical formula for the sum of the series.
The series is 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n)
The nth term of the series is
an = (2 + 4 + 6 + 8 + … + 2n) = (n*n) + n
an is the sum of even numbers upto n.
The sum of the series is
sum = 2 + (2+4) + (2+4+6) + (2+4+6+8) + ... + (2+4+6+8+...+2n) sum = ∑ (n2 + n) sum = ∑ n2 + ∑ n sum = [ (n*(n+1)*(2n + 1))/6 ] + [ (n*(n+1))/2 ] sum = ½ (n*(n+1)) [(2n + 1)/3 + 1] sum = ½ (n*(n+1)) [(2n + 1 + 3)/3] sum = ½ (n*(n+1)) [2(n+2)/3] sum = ? n*(n+1)(n+2)
Example
Program to illustrate the working of our solution,
#include <iostream> using namespace std; int calcSeriesSum(int n) { return ((n)*(n+1)*(n+2)/3); } int main() { int n = 5; cout<<"Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+"<<(2*n)<<") is "<<calcSeriesSum(n); return 0; }
Output
Sum of the series 2 + (2+4) + (2+4+6) + ... + (2+4+6+...+10) is 70