In this problem, we are given two numbers n and k for a series. Our task is to create a program to find sum of given sequence in C++.
The sequence is −
(1*2*3*...*k) + (2*3*...k*(k+1)) + (3*4*...*k*k+1*k+2) + ((n-k+1)*(nk+ 2)*... *(n-k+k).
Problem description − Here, we will find the sum of the given series till nth term based on the given value of k.
Let’s take an example to understand the problem
Input
n = 4, k = 3
Output
30
Explanation
Series: (1*2*3) + (2*3*4) = 30
Solution Approach
A simple solution is to find the sum using iteration. We will use two loops, one for each term and second for finding the value of the term. Then adding the value of each term to get the result.
Program to illustrate the working of our solution
Example
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
int sumVal = 0, term = 1;
for(int i = 1; i <= (n-k + 1); i++){
term = 1;
for(int j = i; j< (k+i); j++){
term *= j;
}
sumVal += term;
}
return sumVal;
}
int main(){
int n = 4, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}Output
The sum of series is 30
This solution is not efficient as it needs a nested loop that makes the time complexity of the order O(n2).
An efficient solution could be using the general formula for the series. The formula is,
$\frac{(\square+1)*\square*(\square-1)*(\square-2)*....*(\square-\square+1)}{\square+1}$
Program to illustrate the working of our solution
Example
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
int sumVal = 1;
for(int i = n+1; i > n-k; i--)
sumVal *= i;
sumVal /= (k + 1);
return sumVal;
}
int main(){
int n = 4, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}Output
The sum of series is 30