• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
November 16, 2022 |1.2K Views

C++ Program to Find Sum of Sequence

  Share   Like
Description
Discussion

In this video, we will write a C++ program to find the sum of the sequence 

Given two numbers N and K. The task is to find the sum of the sequence given below. 

(1*2*3*…*k) + (2*3*…*k*(k+1)) + (3*4*..*(k+1)*(k+2)) +…..+((n-k+1)*(n-k+2)*…*(n-k+k)). 

Since the output can be large, print the answer under modulo 10^9+7. 
Examples
Input : N = 3, K = 2 
Output: 8 
Dry run: 1*2+2*3= 8 

Methods for finding the sum of sequence

In the first method, we find the sum using iteration, where we will use two loops, one for each term and the second for finding the value of the term. At last, add the value of each term to get the desired output. 

Here due to the nested loop, the time complexity is O(n^2).

In the second approach, we use only one for a loop. This for loop is used to calculate the sum up to n.