Preprocess the binomial coefficient mod a prime number MOD with time cost of O(n)

First remember that \binom{n}{m}=\frac{n!}{m!(n-m)!}, and all we have to do is to calculate all the n fatorials, namely Factorial[i]=i!, 0<=i<=n and their corresponding inverses Factorial_Inverse[i] in O(n) time. And when we want to calculate certain binomial coefficient, we simply need to multiple three numbers that have been preprocessed by us, namely, Factorial[n], Factorial_Inverse[m], Factorial_Inverse[n-m].

    For Factorial[i], it is quite trivial.

Factorial[0]=1;

for(int i=0;i<=n;i++)Factorial[i]=(Factorial[i-1]*i)%MOD;

    For Factorial_Inverse[i], it is a bit more complicated. if we tend to get the inverse in linear time, we have to kind of use the information that has been calculated several steps before. Thus we only need to traverse the whole n-length long array once, with time cost if O(n).

    When we want to calculate Factorial_Inverse[i], we want to use the information of Factorial_Inverse[1...i-1]. Thus we do the following observation. Let t=MOD/i, k=MOD%i, and t*i+k\equiv0 (mod MOD). Multiple both sides of this equation by Factorial_Inverse[i] and Factorial_Inverse[k], we get t*Factorial_Inverse[k]+Factorial_Inverse[i]\equiv0 (mod MOD).

    Conclusion Factorial_Inverse[i]\equiv-MOD/i*Factorial_Inverse[MOD%i] (mod MOD), with MOD%i<i. And see how we used the information calculated before.

    Rewrite this equation we have Factorial_Inverse[i]=(MOD-MOD/i*Factorial_Inverse[MOD%i])%MOD.

    And to save more time, we continue to preprocess Factorial_Inverse[i] by multiplying the previous i terms together.

Factorial[1]=1;

for(int i=2;i<=n;i++)Factorial_Inverse[i]=(MOD-MOD/i*Factorial_Inverse[MOD%i])%MOD;

for(int i=2;i<=n;i++)Factorial_Inverse[i]=(Factorial_Inverse[i]*Factorial_Inverse[i-1])%MOD;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值