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
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)$.
Python3
class Solution:
def trailingZeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
Java
class Solution {
public int trailingZeroes(int n) {
int ans = 0;
while (n > 0) {
n /= 5;
ans += n;
}
return ans;
}
}
C++
class Solution {
public:
int trailingZeroes(int n) {
int ans = 0;
while (n) {
n /= 5;
ans += n;
}
return ans;
}
};
Go
func trailingZeroes(n int) int {
ans := 0
for n > 0 {
n /= 5
ans += n
}
return ans
}
TypeScript
function trailingZeroes(n: number): number {
let ans = 0;
while (n) {
n = Math.floor(n / 5);
ans += n;
}
return ans;
}
Swift
class Solution {
func trailingZeroes(_ n: Int) -> Int {
var count = 0
var number = n
while number > 0 {
number /= 5
count += number
}
return count
}
}