Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++

C++Server Side ProgrammingProgramming

In the problem, we are ginen two number k and n of the series K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^2 ) + ... (K-1)^n. 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, k = 4
Output: 175
Explanation: Sum of the series is
= 4^3 + ( (4^2)*(3^1) ) + ( (4^1)*(3^2) ) + ( (4^0)*(3^3) )
= 64 + 48 + 36 + 27 = 175

A simple way to solve the problem, is using a for loop. Find each term of the series and add the value to the sum.

Algorithm

initialise sum = 0;
Step 1: for i -> 0 to n.
Step 1.1: update sum: sum += pow(k, n-i) * pow(k, i)
Step 2: return sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int calcSeriesSum(int k, int n) {
   int sum = 0;
   for (int i = 0; i <= n; i++) {
      int p = pow(k, n-i) * pow((k-1), i);
      sum = sum + p;
   }
   return sum;
}
int main() {
   int n = 4;
   int K = 2;
   cout<<"Sum of the series is "<<calcSeriesSum(K, n);
}

Output

Sum of the series is 31

This solution is not efficient and takes time of the order n.

An efficient solution will be finding the general formula for the sum of the series.

The series K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^2 ) + ... (K-1)^n
Forms a geometric progression. The common ration of this progression is (k-1)/k and the first term is k^n.
sum = K^n + ( K^(n-1) * (K-1)^1 ) + ( K^(n-2) * (K-1)^2 ) + ... (K-1)^n
sum = kn(1 + (k-1)/k + (k-1)2/k2 + … + (k-1)n)
sum = ((kn)(1 - ( (k-1)(n+1))/k(n+1))) / (1 - ((k-1)/k))
sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) / ( (k - (k-1))/k )
sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) / (1/k)
sum = kn ( (k(n+1) - (k-1)(n+1))/k(n+1) ) * k
sum = ( k(n+1) - (k-1)(n+1) )

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int calcSeriesSum(int k, int n) {
   return ( pow(k,(n+1)) - pow((k-1),(n+1)) );
;
}
int main() {
   int n = 4;
   int K = 2;
   cout<<"Sum of the series is "<<calcSeriesSum(K, n);
}

Output

Sum of the series is 31
raja
Published on 17-Aug-2020 13:46:40
Advertisements