Math behind “compute n! under modulo p”?

拥有回忆 提交于 2019-12-02 09:23:08

The basic idea here is that you can take the modulus before, during, or after multiplication and get the same value after taking the modulus of the final result.

As @Peter points out,

(a * b) % m == ((a % m) * (b % m)) % m

For the factorial,

n! = 1 * 2 * 3 * ... * (n-1) * n

so we have

n! % m = (((((((1 * 2) % m) * 3) % m) * ... * n-1) % m) * n) % m

taking the modulus after each iteration.


The advantage to doing it this way is that your number won't blow up and overflow your long long type like it would do pretty quickly if you didn't take intermediate modulus values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!