Program to find Sum of a Series a^1/1! + a^2/2! + a^3/3! + a^4/4! +…….+ a^n/n! in C++


In this problem, we are given two numbers a and n. Our task is to create a program to find Sum of a Series a^1/1! + a^2/2! + a^3/3! + a^4/4! +…….+ a^n/n! in C++.

Problem description − The problem is to find the sum of the given series using the given values of a and n. The series is a special series in which each term is the multiple of the last term with a/i, i -> 1 to n.

Let’s take an example to understand the problem

Input

a = 3, n = 4

Output

15.375

Explanation

sum of series is

(3^1)/1! + (3^2)/2! + (3^3)/3! + (3^4)/4! = 3 + 9/2 + 27/6 + 81/24
= 15.375

Solution Approach

To find the sum of the series, we will use loops to find the ith term of the series and add them to find the sum.

The computation of each element of the series directly has calculation overhead. So, we will use last term to find the next term.

Here, ith term = (i-1)th term * a/i.

Using this we will find terms with less calculations that improves the overall performance of the code.

Program to illustrate the working of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
float calcSeriesSum(int a, int n){
   float sumVal = 0, term = 1;
   for(float i = 1; i <= n; i++){
      term *= a/i;
      sumVal += term;
   }
   return sumVal;
}
int main(){
   int a = 3, n = 4;
   cout<<"The sum of the series is "<<calcSeriesSum(a, n);
   return 0;
}

Output

The sum of the series is 15.375

Updated on: 16-Sep-2020

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements