Maintained by Vikas Dulgunde, software engineer
The factorial n! is the product of every integer from 1 up to n, so it grows enormously fast. Even for moderate n the value is far too large to hold in a normal integer type, so any approach that builds the factorial and inspects its digits is doomed on the larger inputs.
A trailing zero appears only when the product picks up a factor of 10. Every 10 is the result of one factor of 2 multiplied by one factor of 5, so the count of trailing zeroes equals the number of complete (2, 5) pairs hidden inside the product.
Inside a factorial the even numbers supply factors of 2 far more often than any number supplies a factor of 5. Twos are never the bottleneck, so the answer is simply the total number of times 5 divides into n!.
Return that total count of 5s. Note that some numbers contribute more than one five: 25 is 5 times 5, 125 is 5 times 5 times 5, and so on, so those higher powers must be counted again.
5! = 120, which ends in a single zero. Among 1 through 5 only the number 5 carries a factor of 5, so there is exactly one 5 and one trailing zero.
The multiples 5, 10, 15, 20, 25 each give at least one 5 (five of them), and 25 = 5 times 5 gives an extra one, for a total of six factors of 5.
3! = 6 has no factor of 5 anywhere, so there are no trailing zeroes.
Visible test cases
You cannot compute n! directly for large n, so look for a property of the digits instead of the digits themselves.
A trailing zero comes from a factor of 10, and 10 = 2 times 5. Which of those two prime factors is the scarce one inside a factorial?
Count factors of 5: add floor(n/5), then floor(n/25), then floor(n/125), and keep going while the power of 5 is at most n.
Multiply 1 through n into a big integer, then peel off trailing zeroes by repeatedly checking divisibility by 10.
The number of trailing zeroes equals the number of times 5 divides n!, because factors of 2 are always at least as plentiful. Sum floor(n / 5^k) over increasing powers of 5.