Trailing Zeroes of n!
Problem
Return the number of trailing zeroes in n! (n factorial). Don't compute the factorial directly — n can be huge.
Input
n = 100Output
24A trailing zero comes from a factor of 10 = 2 · 5. There are always more 2s than 5s in 1·2·…·n, so just count the 5s: ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + …
def trailing_zeroes(n):
count = 0
while n > 0:
n //= 5
count += n
return count
function trailingZeroes(n) {
let count = 0;
while (n > 0) {
n = Math.floor(n / 5);
count += n;
}
return count;
}
class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
}
int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}