Trailing Zeroes of n!

medium math

Problem

Return the number of trailing zeroes in n! (n factorial). Don't compute the factorial directly — n can be huge.

Inputn = 100
Output24
A 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;
}
Time: O(log₅ n) Space: O(1)