We assume that P is prime, n! =a*pe, we need to solve a mod p and E.
E is n! The number of times that divisible p can be iterated, so use the following formula:
N/p+n/p2+n/p3 ...
We only need to calculate the pt≤n T, so the complexity is O (LOGPN)
Next calculate a mod p.
First calculate the n! The product of an item that cannot be divisible by P in the factor.
As a simple example, it is not difficult to find that items that cannot be divisible by P are periodically under mod p.
Therefore, the n! can be The sum of the items in the factor that cannot be divisible by P is as follows:
(p-1)! (n/p) * (n mod p)!.
According to Wilson's theorem, we have (p-1)! ≡-1. So this time we just need to ask for n/p's parity and (n mod p)! You can do it.
//Wilson theorem and proof see: http://www.cnblogs.com/wls001/p/5160288.html
Then we only have to preprocess the range of 0<=n<p n! MoD P's table will be able to calculate the answer in O (logp N) time. If not preprocessed, then the complexity is O (P logp N).
N! MoD P's method of finding