Computer Science, asked by bhargavijoshi4, 1 year ago

write a program in c++ to find the sum of the sequence 
1+1/1!+1/2!+1/3!.........

it is one + one by 2 factorial+ one by 3 factorial and so onn.......plzz help...

Answers

Answered by tithi
2
#include <iostream> 
int main() 

     std::cout << "How many terms to calculate? "; 
     int n; 
     std::cin >> n; 

     double sum = 0; 
     double product = 1; 
     for(int k=1; k<=n; ++k) 
     { 
         product *= k; 
         sum += 1/product; 
     } 

     std::cout << "The answer is " << sum << '\n'; 



and, just for fun, here's how it can be done without loops, in C++0x: 

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <cmath> 
int main() 

     std::cout << "How many terms to calculate? "; 
     int n; 
     std::cin >> n; 
     std::vector<double> v(n); 
     iota(v.begin(), v.end(), 1); 
     transform(v.begin(), v.end(), v.begin(), [](double i){return 1/tgamma(i+1);}); 
     double sum = accumulate(v.begin(), v.end(), 0.); 
     std::cout << "The answer is " << sum << '\n'; 

hope i helped u:)

tithi: plzzzz mark as best
Similar questions