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.
Solution 1: Mathematics
The problem is actually asking for the number of factors of
Let's take
- 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
class Solution:
def trailingZeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
class Solution {
public int trailingZeroes(int n) {
int ans = 0;
while (n > 0) {
n /= 5;
ans += n;
}
return ans;
}
}
class Solution {
public:
int trailingZeroes(int n) {
int ans = 0;
while (n) {
n /= 5;
ans += n;
}
return ans;
}
};
func trailingZeroes(n int) int {
ans := 0
for n > 0 {
n /= 5
ans += n
}
return ans
}
function trailingZeroes(n: number): number {
let ans = 0;
while (n > 0) {
n = Math.floor(n / 5);
ans += n;
}
return ans;
}