Factorial Trailing Zeroes

Source: Internet
Author: User

Given an integer n, and return the number of trailing zeroes in n!.

Note:your solution should is in logarithmic time complexity.

Analysis
First of all, don't forget what is factorial, or factorial. Then it is easy to think of the number of statistics (2,5) required, because 2x5=10. But the condition of relaxation will find that only a few 5 of the number is good, because 2 is actually more than 5.
Then the title translates into the sum of approximately 5 of the numbers from 1 to N. It is very simple to think that you can get it with N/5. For example, when n is 19, 19/5 = 3.8, then there are 3 approximate numbers with 5, 5, 10, 15, respectively. But some of the numbers may be divisible by 5, say 25. Such a number can contribute several 5 to the final factorial.
The final solution is to sum the n/5+n/25+n/125+...+ and stop when n is less than the denominator. The denominator in turn is 5^1, 5^2, 5^2 ... In this case, in the calculation of 5^2, can be divisible by 25 of the number of two 5, one of which has been calculated in the 5^1. So the 5^2 is added directly to count.

[Precautions]
1) Note that the requirement of the title is logarithmic time complexity, so for the for loop, I changes must not be linear, need to be multiplication (increment) or division (decrement).
2) If the interview is tested, talk to the interviewer about the dumbest way. Then give a few examples.
3) Pay attention to the handling of n<0 [Code]

1  Public classSolution {2      Public intTrailingzeroes (intN) {3         if(n<0)return-1;4         intCount = 0;5          for(Longi=5; n/i>=1; I*=5) {6Count + = n/i;7         }        8         returncount;9     }Ten}

Reference:http://www.danielbit.com/blog/puzzle/leetcode/leetcode-factorial-trailing-zeroes

Factorial Trailing Zeroes

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.