O(n)预处理C(n,m)

fac[n] = n! = fac[n-1]*n

f[n] = inv(n) = (mod - mod / n) * f[mod%n]

inv[n] = inv(n!) = inv[n-1] * f[i]


关于f[n]递推式的证明

inv(n)==(mod - mod/n) * inv(mod%n)   (% mod)

两端同时乘上n, 可得1==n*(mod - mod/n) *inv(mod%n)   (%mod)

接下来证明该式成立:

    n*(mod - mod/n) *inv(mod%n)    (% mod)

= mod*n-(mod-mod%n)*inv(mod%n)   (%mod)

= mod%n*inv(mod%n)

=1

const int maxn=1000100;
const int mod=1000000007;
typedef long long LL;
LL fac[maxn],f[maxn],inv[maxn];
void init()
{
    fac[0]=fac[1]=f[0]=f[1]=inv[0]=inv[1]=1;
    for(int i=2;i<maxn;i++)
    {
        fac[i]=fac[i-1]*i%mod;
        LL t=mod/i,k=mod%i;
        f[i]=(mod-t)*f[k]%mod;
        inv[i]=inv[i-1]*f[i]%mod;
    }
}
LL c(LL n,LL m)
{
    if(n<m) return 0;
    return fac[n]*inv[m]%mod*inv[n-m]%mod;
}

你可能感兴趣的:(排列组合)