Fast obtaining n! Number of prime factors

Generally do the number of combinations of the subject should be carried out decomposition of the quality factor, we generally are for each cycle of prime factorization, most cases are not time out, but in rare cases, the subject will not allow such an approach so we need to learn a faster way to find prime factors.

Our general approach is to perform prime factorization of each number:

. 1 inline void Calc ( int X)
 2  {
 . 3      int XX = X;
 . 4      for ( int I = 2 ; I * I <= XX; I ++ )
 . 5      {
 . 6          the while (I X% == 0 ) // continuous division current prime number, number identified 
. 7          {
 . 8              C [I] ++; X / = I;
 . 9          }
 10          IF (X == . 1 ) BREAK ;
 . 11      }
 12 is      IF (X> . 1 ) C [X] ++ ;// If the remaining count is also a substance, then this should be prime plus 
13 }

But if you want a faster decomposition, we can directly n! Decomposition:

First of all primes were first screened drawn prime table

Then proceed as follows:

. 1 inline Long  Long Calc ( int n, int x) // x represents the number of interstitial, would like to request a function of x is the number obtained, the required n represents n! (Example: n = 8 represents 8!) 
2 {    Long  Long CNT = 0 ;
 . 3      for ( Long  Long i = X; i <= n-; i * = X) // to prevent overflow i, so we should start and Long Long 
. 4        {CNT + = n-/ i;    
 . 5              } 
 . 6      return CNT;
 . 7      }

Let's explain a sample:

12345678 8 we find! The number 2

     1111 First we calculate the number of multiples of 2: 8/2 = 4

            11 Second, we calculate the number of multiples of 4: 8/4 = 2 (obtained from the expressions above, a first layer, the second layer is now seeking)

                            Finally, we solve a number of the third layer is 2: 8/8 = 1

We have 4 + 2 + 1 = 7, so there have been a total of seven 2.

 Namely: cnt (x) = [n / (x ^ 1)] + [n / (x ^ 2)] + [n / (x ^ 3)] + ... (x until power is greater than n)

Here we can find: the way we usually find is a one demand of (each number is the count again), and this way we seek each line of each row, although the effect is the same, but for up fast. worth learning.

So practice:

  1. The first prime number table lay

  2.for each cycle the number n of mass less than one operation performed by the recording array

  3. End

very fast.

Guess you like

Origin www.cnblogs.com/tldr/p/11615239.html