Find sum of the series 1+22+333+4444+... upto n terms in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer value N. Our task is to find Sum of Series 1 + 22 + 333 + 4444 + 55555... upto n terms.

Let's take an example to understand the problem,

Input : N = 4
Output : 4800

Explanation

1 + 22 + 333 + 4444 = 4800

Solution Approach

A simple approach to solve the problem is finding the general term of the series and then finding the sum till n terms. And calculating the sum using formula will reduce the time to O(1).

The series is,

1 + 22 + 333 + 4444 + 55555...

Sum of series can be rewritten as,

$\mathrm{Sum}\:=\:1^*(\frac{10^1-1}{9})\:+\:2^*(\frac{10^1-1}{9})\:+\:3^*(\frac{10^1-1}{9})\dotsm$

Taking 1/9 common the sum becomes,

$\mathrm{Sum}\:=\:1/9^*\lbrace(1^*10^1-1)\:+\:(2^*10^2-1)\:+\:(3^*10^3-1)\:+\:\dotsm(n^*10^1-n)\rbrace$

$\mathrm{Sum}\:=\:1/9^{*}\lbrace1^*10^1\:+\:2^*10^2\:+\:3^*10^3\:+\:\dotsm+n^*10^n\:-\:(1+2+3+\dotsm\:n)\rbrace$

$\mathrm{Sum}\:=\:1/9^{*}\lbrace(1^*10^1\:+\:2^*10^2\:+\:3^*10^3\:+\:\dotsm+n^*10^n)\:-\:1/2(n^*(n+1))\rbrace$

The term (1*101 + 2*102 + 3*103 + ... + n*10n) can be solved by differentiating the general formula for series,

1 + x + x2 + x3 + ... n*xn

So, the terms (1*101 + 2*102 + 3*103 + ... + n*10n) can be rewritten as,

$\frac{n^*(10^{n+2})-(n+1)*(10^{n+1})+10}{81}$

Putting back in sum formula,

$\mathrm{Sum}\:=\:1/9^*\lbrace(\frac{n^*(10^{n+2})-(n+1)*(10^{n+1})+10)}{81}\:-\:1/2(n^*(n+1))\rbrace$

$\mathrm{Sum}\:=\:\frac{1}{1458}*\lbrace2^*(n*(10^{n+2})-(n+1)*(10^{n+1})+10)-81^*n^*(n+1)\rbrace$

$\mathrm{Sum}\:=\:\frac{1}{1458}*\lbrace2^*(n*(10^{n+2})-(n+1)*(10^{n+1})+10)-81^*n^*(n+1)\rbrace$

$\mathrm{Sum}\:=\:\frac{1}{1458}*\lbrace(n^*(2^*10^{n+1}-2^*10^{n+1})-2^*10^{n+1})\:+\:20\:-\:81^*n^2-81n\rbrace$

$\mathrm{Sum}\:=\:\frac{1}{1458}*\lbrace10^{n+1*}(20n-2n-2)-81n^2-81n+20\rbrace$

$\mathrm{Sum}\:=\:\frac{1}{1458}*\lbrace10^{n+1*}(18n-2)-81n^2-81n+20\rbrace$

Example

Program to illustrate the working of our solution

#include<iostream>
#include<math.h>
using namespace std;
int calcSumNTerms(int n) {
   return ( ( (18*n - 2)*(pow(10, n+1)) - 81*n*n - 81*n + 20 )/1458 );
}
int main() {
   int n = 5;
   cout<<"The sum of series upto n terms is "<<calcSumNTerms(n);
   return 0;
}

Output

The sum of series upto n terms is 60355
raja
Updated on 27-Jan-2022 08:49:02

Advertisements