C program: Sum of factorials 1! + 2! + 3!+ ...+ n!?

Hi there! :slight_smile:

Here are my codes:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    long n,m,s=0,h=1;
    scanf("%d",&n);
    for(m=1;m<=n;m++)
    {
        h=h*m;
        s=s+h;
    }
    printf("%ld",s);
    return 0;
}

But it does not work at all somewhere after n=12, because of ‘overflow’. I tried ‘long long’ but that did not work either.

What should I do to make this work? I’d appreciate any help and advice. :sunny:

1 Like

Did you tried to use double? It depends on how far you want to go, if you keep overflowing you can search for a library that handle big numbers.

Right, it works! And I tried using “long long” again and made it. But what’s weird is that there is a small difference between the results output by lld and lf, like, the former is more accurate than the latter. Can I ask why?

Really? Long should be more accurate than double, but less capable of storing big numbers. Also, you can use long double if you want.

It’s best if I link you for a proper answer.

1 Like

Yeah, this helps me. Thank you!