problem Source: https://leetcode.com/problems/factorial-trailing-zeroes/
Problem Description: Given an integer N , return the number of trailing zeroes in N !. Note: Your solution should is in logarithmic time complexity. (requires a trailing 0 number to return the value n! note the complexity)
My Code (3MS):
1) First simplify the problem (avoid factorial): n! decomposition =2x * 3y * 5z * ...; Obviously we ask for Min (x,z) and Min (x,z) ==z;
2) Next how to represent the number of 1~n that can be divisible by k: [n/k]
3) Proof: for factorial, which is 1*2*3*...*n, it is clear that:
[N/2] > [N/5] (on the left is 2 increase 1, the right is 5 increase 1)
[N/2^2] > [n/5^2] (on the left is 4 increase 1, the right is 25 increase 1)
[N/2^p] > [N/5^p] (on the left is the 2^p increase 1, on the right is every 5^p 1)
With the rise of power p, the probability of appearing 2^p is much greater than the probability of 5^p. So the left side of the addition and must be greater than the right side of the sums, that is, n! quality factor decomposition, 2 of the power must be greater than 5 recurses; so the right and the answer.
int trailingzeroes (int n) {
int count = 0;
while (n) {
count + = N/5;
n = n/5;
}
return count;
}