
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 + 2 + 1 + 2 + 3 + 1 + 2 + 3 + 4 + ... + n in C++
In this problem, we are given a number n. Our task is to create a program to find the sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + … + (1+2+3+4+...+n).
Lets example to understand the problem,
Input
n = 4
Output
20
Explanation −(1) + (1+2) + (1+2+3) + (1+2+3+4) = 20
A simple solution to the problem will be creating the series by using two loops.
Algorithm
Initialize sum = 0 Step 1: Loop for i -> 1 to n i.e i = 1 to i <= n. Step 1.1: Loop for j -> 1 to i i.e. i = 1 to i <= i. Step 1.1.1: update sum i.e. sum += j. Step 2: return sum.
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++) for (int j = 1 ; j <= i ; j++) sum += j; return sum; } int main() { int n = 7; cout<<"Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+"<<n<<") is "<<calcSeriesSum(n); return 0; }
Output
Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+7) is 84
But this approach is not effective.
An effective solution could be deriving the general formula for finding the sum of the series.
sum = 1 + (1+2) + (1+2+3) + (1+2+3+4) … sum = ∑ ( (1+2+3+4+5+...) ) sum = ∑ ( n(n+1)/2) sum = ½ ∑ ( n^2 + n) = ½ (∑ (n2) + ∑ n) sum = ½ [ (n(n+1)(2n+1))/6 ) + ½ ( n(n+1)/2 ] sum = ½ [ (n(n+1))/2 ( (2n+1)/3 + 1) ] sum = ½ [ ((n(n+1))/2) * (2n + 1 + 3)/3 ] sum = ½ [ (n(n+1)(2n+4))/6] sum = (n(n + 1)(2n + 4))/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 + 4))/12; } int main() { int n = 7; cout<<"Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+"<<n<<") is "<<calcSeriesSum(n); }
Output
Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+7) is 84
Advertisements