Sum of the series 1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + upto n terms in C++

C++Server Side ProgrammingProgramming

Here, we are given an integer n. It defines the number of terms of the series 1/1 + ( (1+2)/(1*2) ) + ( (1+2+3)/(1*2*3) ) + … + upto n terms.

Our task is to create a program that will find the sum of series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + … upto n terms.

Let’s take an example to understand the problem,

Input

n = 3

Output

3.5

Explanation −(1/1) + (1+2)/(1*2) + (1+2+3)/(1*2*3) = 1 + 1.5 + 1 = 3.5

A simple solution to this problem is by looping from 1 to n. Then, add the values of the sum of i divided by product upto i.

Algorithm

Initialise result = 0.0, sum = 0, prod = 1
Step 1: iterate from i = 0 to n. And follow :
   Step 1.1: Update sum and product value i.e. sum += i and prod *= i
   Step 1.2: Update result by result += (sum)/(prod).
Step 2: Print result.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   double result = 0.0 ;
   int sum = 0, prod = 1;
   for (int i = 1 ; i <= n ; i++) {
      sum += i;
      prod *= i;
      result += ((double)sum / prod);
   }
   return result;
}
int main() {
   int n = 12;
   cout<<"Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto "<<n<<" terms is "   <<calcSeriesSum(n) ;
   return 0;
}

Output

Sum of the series 1/1 + (1+2)/(1*2) + (1+2+3)/(1*2*3) + ... upto 12 terms is 4.07742
raja
Published on 14-Aug-2020 13:32:01
Advertisements