The beauty of programming should not be intimidated by the factorial, but the beauty of 2.2.
When I first saw this question, I thought it was the idea to use a string to represent the integer number. Later I saw that because it is a factorial of a number, if it is large, therefore, it is unreasonable to use the string representation. After reading the explanation of this question, the book gives a formula and then understands the meaning of the question.
First, I will post the function declaration and question requirements:
/* 2.2 do not be intimidated by the factorial * // * 2.2.1 N! The number of zeros at the end of */int dutcountof0infactoria1( int);/* 2.2.2 N! The binary value of */int dutpositionof1infactoria1( int );
We think that there is a number of N, so how many c (c> = 1 & c <= 9) exist in 1-N? We can use this formula to calculate:
The formula for calculating the number of numbers of x in 1-N is N/x + N/x2 + N/x3 +..., and the formula must converge at last.
Therefore, you can write the following code:
/* 2.2.1 N! The number of zeros at the end of the question * // the idea of solving this question is: 2*5 = 10. Therefore, we only need to confirm that there are several 5 in 1-N (because 2 has many) */int dutcountof0infactoria1n (int n) {if (n <= 0) return 0; int count = 0;/* the formula for calculating the number of x in 1-N is: N/x + N/x2 + N/x3 + ..., and this formula must eventually converge */while (n) {n + = n/5; n/= 5 ;} /* return the number of 0 at the end */return count;}/* 2.2.2 N! Binary represents the position of the second digit 1 * // * indicates the second digit 1 in the binary. Therefore, you need to know how many zeros exist next to it. Therefore, we only need to determine how many 2 s there are. */int dutpositionof1infactoria1( int n) {if (n <= 0) return 0; int count = 0; /* the formula for calculating the number of x in 1-N is: N/x + N/x2 + N/x3 + ..., and this formula must eventually converge */while (n) {count + = n/2; n/= 2;} return count + 1 ;}