Calculate sum of 1+(1/2!)+…+(1/n!) n number in C language

后端 未结 4 1426
情歌与酒
情歌与酒 2021-01-24 08:44

Like the title say, how I calculate the sum of n number of the form: 1+(1/2!)+⋯(1/n!)? I already got the code for the harmonic series:

#include 

         


        
4条回答
  •  耶瑟儿~
    2021-01-24 09:25

    Calculating factorial in this case is bad thing to do because it can cause overflow for small values of N . Use following pseudo code to get it in O(N) without overflow.

    double sum = 0.0;
    double acc = 1;
    double error = 0.0000001;
    
    for(i=1;i<=n;i++) {
       acc = acc/i;
       if(acc

    More acurrate way of doing it though i feel it is unnecessary in case of factorials : -

    double sum = 0.0;
    double acc = 1;
    
    for(i=n;i>=1;i--) {
    
       sum = (sum + 1)/i;
    }
    
    print(sum);
    

    Note:- Because the above method is built in reverse it more accurate but unfortunately more time consuming because it is O(N) even for higher values whereas the gain in accuracy is negligible as factorial function grows very fast hence error keeps on decreasing quickly.

提交回复
热议问题