Factorial Trailing Zeroes -- leetcode
Given an integer n, return the number of trailing zeroes in n !.
Note: Your solution shocould be in logarithmic time complexity.
Basic Ideas:
Count n! The number of tails 0.
The ending number 0 is obtained by the product of 2, 5.
To count the number of 0, you need to count the number of 2, 5 factors. Because the number of 2 is more than 5, you only need to count the number of 5 factors.
For example, 5, 10, 15, 15, 20 n * 5, contains a 5.
25, 50, 75, n * 25, containing 2 5.
N * 125 contains 3 5.
...
Because the latter has an intersection with the former, the former has been counted. Therefore, you only need to add the latter one more time.
return n/5 + n/25 + n/125 + n/625 + n/3125+...;
Or write:
N/5 + (n/5)/5 + (n/5/5)/5 + (n/5/5/5)/5
class Solution {public: int trailingZeroes(int n) { int ans = 0; int count = 0; while (n) { n /= 5; ans += n; } return ans; }};
return n/5 + n/25 + n/125 + n/625 + n/3125+...;