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.
begin res := 0 denominator := 1 for i in range 1 to n, do denominator := denominator * i res := res + i / denominator done return res end
#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); }
Enter number of terms: 5 Result: 2.70833
Enter number of terms: 3 Result: 2.5