Set N! Expressed
N! = P1 ^ t1 * p2 ^ t2 *... Pi ^ ti... * Pk ^ tk (p1, p2 ...... Pk is a prime number, 1 <N <= 10 ^ 6)
Obviously, it is easy to obtain pi through Prime Number filtering, because 1 <pi <= N, the key is how to quickly find ti.
Let's first take a look at the prime factor 2, putting N! It is divided into two parts: the parity
Assume that N is an even number.
N!
= 1*2*3*4*5 ...... N
= (2*4*6 ......) * (1*3*5 ......)
Because N/2 even numbers exist, N/2 2 2 numbers can be proposed for the even number,
= 2 ^ (N/2) * (1*2*3 *...... N/2) * (1*3*5 *......)
= 2 ^ (N/2) * (N/2 )! * (1*3*5 *......)
Have you seen it! The magic happened, and the N scale problem was transformed into the N/2 problem. It is assumed that N is an even number, and N is an odd number, as long as the division here is an integer.
So there is a recursive formula f (n, 2) = f (n/2, 2) + n/2, indicating n! The number of 2.
In the same way, f (n, p) = f (n/p) + n/p, indicating n! Number of prime p in.
So there is code
int f(int n,int p)
{
if(n==0) return 0;
return f(n/p) + n/p;
}
Spread the problem as follows:
Question 1: N! How many zeros are there at the end?
Because 10 = 2*5, you only need to know N! The problem is solved when there are two and five. Min (f (n, 2), f (n, 5) obviously f (n, 2)> f (n, 5 ), so the problem is transformed into f (n, 5 ).
Question 2: N! After it is converted into a 12-digit system, how many zeros are there at the end?
As with the problem, 12 = 2*2*3, so only Min (f (n, 2)/2, f (n, 3) is required.
Question 3: calculate the number of combinations C (n, m) (mod p)
C (n, m) = n! /(M! * (N-m )!) As long as the numerator and denominator are decomposed into prime factors separately, then C (n, m) must be an integer, So C (n, m) it can be expressed as p1 ^ t1 * p2 ^ t2 *...... pi ^ ti form, as long as the power of the molecular prime factor minus the power of the prime factor corresponding to the denominator. Okay, it's easy to follow. The binary fast power modulo ......