- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find sum of given sequence in C++
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).
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
Advertisements