[Leetcode] Factorial Trailing zeroes factorial end 0

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.