1. Brief Introduction
1) given an integer N, then the factorial N of N! How many zeros are there at the end? Example: N = 10, N! = 3 628 800, N! There are two zeros at the end.
2) calculate N! In binary format.
2. Ideas
Method 1: Obtain N !, For the first question, just record the number of 0, time complexity = O (N) + O (N! The number of 0). For the second question, record the number of 0 to the right of the second digit 1 in binary. the time complexity = O (N) + O (N! ). The time complexity of this method is not big, but there is a space problem, because N! The growth is too fast. N doesn't need to be large, N! It is easy to overflow.
Method 2: N is not required !, From N! The first question is to calculate N! Medium, the number of Factor 5, because each 0 is a 10, 10 = 2*5, factor 2 obviously far exceeds 5, so the number of 10 (that is, the number of 0) the number is the same as 5. The second question is to calculate N! The number of factor 2 in the binary representation. The number of factor 2 is the number of 0 after the first digit 1, that is, if N! If there are k factors 2, then the first digit 1 is followed by k zeros.
In this way, the two questions are converted into N! Number of factors C. N !, Calculate the number of the factor C from 1, 2,..., N, and then sum. Here is a method mentioned in the beauty of programming, which is faster. Number of factors = [N/C] + [N/(C ^ 2)] + [N/(C ^ 3)] + ·, complexity, for example, if C ^ k> N exists, so k is the base N logarithm of C. N is more important than N !, No overflow. Note: [] in [N/C] indicates downgrading.
3. Code
# Include <iostream>
# Include <bitset>
Using namespace std;
Int get_factor_num (int N, int C ){
Int num = 0;
While (N/= C )! = 0)
Num + = N;
Return num;
}
Int get_factorial (int N ){
Int num = 1;
While (N> 0)
Num * = N --;
Return num;
}
Int main (){
Int N;
Cout <"input N :";
Cin> N;
Cout <"N! In decimal format: "<get_factorial (N) <endl;
Bitset <32> NSet (get_factorial (N ));
Cout <"N! "<NSet <endl;
Cout <"N! Number of zeros at the end: "<get_factor_num (N, 5) <endl;
Cout <"N! "<Get_factor_num (N, 2) + 1 <endl;
System ("PAUSE ");
Return 0;
}
Output result:
4. Reference
The beauty of programming, section 2.2, Do not be scared by the factorial