C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! + …… n/n!

C++Server Side ProgrammingProgramming

Here we will see how we can get the sum of the given series. The value of n will be given by user. We can solve this problem by making a factorial function, and get factorial in each step in the loop. But factorial calculation is costlier task than normal addition. We will use the previous factorial term in the next one. Like 3! is (3 * 2 * 1), and 4! is 4 * 3!. So if we store 3! into some variable, we can use that and add the next number only to get the next factorial easily.

Algorithm

sum_series_fact(n)

begin
res := 0
denominator := 1
for i in range 1 to n, do
denominator := denominator * i
res := res + i / denominator
done
return res
end

Example

Live Demo

#include<iostream>
using namespace std;
float series_result(int n) {
float denominator = 1;
float res = 0;
for(int i = 1; i<= n; i++) {
denominator *= i;
res += float(i/denominator);
}
return res;
}
main() {
int n;
cout << "Enter number of terms: ";
cin >> n;
cout << "Result: " << series_result(n);
}

Output

Enter number of terms: 5
Result: 2.70833

Output

Enter number of terms: 3
Result: 2.5
Published on 25-Jul-2019 10:00:35