计算大范围模数的阶乘给出溢出

pra*_*nay 3 math factorial

我试图计算一系列整数的因子(2 <= n <= 10 ^ 7),并且模数如下:

MAXN = 10000000
typedef unsigned long long ULL;
ULL MOD =  109546051211ULL;
ULL factorial[MAXN+1];

void preFact()
{
    factorial[0] = factorial[1] = 1;
    int i;
    for(i = 2;i<=MAXN;i++)
    {
        ULL temp = factorial[i-1]%MOD;
        ULL temp2 = i%MOD;

        temp = (temp*temp2)%MOD;
        factorial[i] = temp;
    }
    printf("%llu %d\n",factorial[i-1],i);
}
Run Code Online (Sandbox Code Playgroud)

但是上面的print语句给出了value = 0.事实上,对于所有n> = 587117,我得到factorial [n]%MOD的值为0.我无法得到溢出的地方以及如何纠正它?谢谢.

Dan*_*her 7

没有溢出,结果是正确的.

109546051211 = 186583 * 587117
Run Code Online (Sandbox Code Playgroud)

所以n >= 587117,我们有n! % 109546051211 = 0.