Given an integer n, return the number of trailing zeroes in N!.
Note:your solution should is in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide TagsMath This should be the end of 2014 to modify the test sample, the previous by traversing 1-n and then determine the number of 5 factors, this simple traversal method is not, time limit. Then, since can not traverse, can only change a thought, can constitute the end of 0, in fact, the determining factor is the number of 1 to n a total of how many 5 factors. So we consider this: for 5 then divisible by him is 5 10 15 25 30 ... In fact, there is a total of N/5, for 25 50 such a number includes two 5 factors, which we will calculate later, when considering 5, the result is N/5. For 25 to be divisible is 25 50 75 ... So, in fact, there are a total of N/25, this time 25 of the two 5 factors, the change is counted. For 125 the same can be divisible by it is 125 625 ... So, is not the result is actually: N/5 + N/25 + n/125 ... This calculation has a problem, will be out of bounds, C + + int type has been multiplied by 5 out of time, will become 1808548329, the topic experiment is the use of this test, so cross-border judgment needs to be considered separately. The code is as follows:
#include <iostream>#include<math.h>#include<vector>using namespacestd;classSolution { Public: intTrailingzeroes (intN) {intRetcnt=0, tmp5=5; while(tmp5<=N) {//cout<<tmp5<< "" <<n<<endl;retcnt+=n/TMP5; TMP5*=5; if(tmp5%5!=0) Break; } returnretcnt; }};intMain () {solution Sol;//for (int i =1;i<=50;i++) {//cout<< "i=" <<i<< ":" <<sol.trailingzeroes (i) <<endl;// }Cout<<sol.trailingzeroes (1808548329) <<Endl; cout<<INT_MAX<<Endl; return 0;}
[Leetcode] Factorial Trailing zeroes factorial end 0