16.05. Factorial Zeros
Description
Write an algorithm which computes the number of trailing zeros in n factorial.
Example 1:
Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
Solutions
Solution 1: Mathematics
Thinking
Trailing zeros of \(n!\) come from factors \(10=2\times 5\). Twos are plentiful, so the count equals the number of fives in \([1,n]\), including higher powers.
Computing \(n!\) and counting zeros overflows for large \(n\).
Repeated \(n//=5\) adds the contributions of \(5\), \(5^2\), \(5^3,\ldots\) in \(O(\log n)\) time.
The problem is actually asking for the number of factors of \(5\) in \([1,n]\).
Let's take \(130\) as an example:
- Divide \(130\) by \(5\) for the first time, and get \(26\), which means there are \(26\) numbers containing a factor of \(5\).
- Divide \(26\) by \(5\) for the second time, and get \(5\), which means there are \(5\) numbers containing a factor of \(5^2\).
- Divide \(5\) by \(5\) for the third time, and get \(1\), which means there is \(1\) number containing a factor of \(5^3\).
- Add up all the counts to get the total number of factors of \(5\) in \([1,n]\).
The time complexity is \(O(\log n)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 | |