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 1 + (1+3) + (1+3+5) + (1+3+5+7) + + (1+3+5+7+....+(2n-1)) in C++
In this problem, we are given an integer n. Our task is to create a program to find the sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + + (1+3+5+7+....+(2n-1)).
From this series, we can observe that ith term of the series is the sum of first i odd numbers.
Let’s take an example to understand the problem,
Input
n = 3
Output
14
Explanation −(1) + (1+3) + (1+3+5) = 14
A simple solution to this problem is using a nested loop and then add all odd numbers to a sum variable. Then return the sum.
Example
Program to illustrate the working of our solution,
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
int sum = 0, element = 1;
for (int i = 1; i <= n; i++) {
element = 1;
for (int j = 1; j <= i; j++) {
sum += element;
element += 2;
}
}
return sum;
}
int main() {
int n = 12;
cout<<"Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2"<<n<<"-1)) is "<<calcSeriesSum(n);
return 0;
}
Output
Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*12-1)) is 650
This approach is not effective as it uses two nested loops.
A more efficient approach is to mathematically find the general formula to find the sum of the series.
Sum of n odd numbers,
= (1) + (1+3) + (1+3+5) + …. (1+3+5+... + 2n-1)
= n2
First, let’s see the sum of first n odd number, which represents the individual elements of the series.
Sum of series,
sum = (1) + (1+3) + (1+3+5) + … + (1+3+5+ … + 2n-1) sum = ∑ (1+3+5+ … + 2n-1) sum = ∑ n2 sum = [n * (n+1) * (2*n -1)]/6
Example
Program to illustrate the working of our solution,
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
return ( n*(n + 1)*(2*n + 1) )/6;
}
int main() {
int n = 9;
cout<<"Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*"<<n<<"-1)) is "<<calcSeriesSum(n);
return 0;
}
Output
Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*9-1)) is 285