First remember that , 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+k0 (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]
0 (mod MOD).
Conclusion Factorial_Inverse[i]-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;
本文介绍了一种快速计算组合数的方法,通过预处理阶乘及阶乘逆元来降低计算复杂度,实现线性时间内求解。

被折叠的 条评论
为什么被折叠?



