Counting trailing zeros of n!¶

Here is a faster algorithm for counting the number of trailing zeros in n!.

The idea is to decompose n! into factors first:

$n! = 1\times 2\times 3 ... \times n = (10^k)\times r$ where k is as large as possible. We now want to figure out what $k$ is. Let's rewrite this again as

$n! = 5^k\times 2^m\times r'$

Here, $m > k$ since there are most factors of 2 available in the product. That means we just need to count up the number of factors of 5 in the product.

S now our just is to count up the number of factors of 5 in the product

$1\times 2\times .. \times 5\times 6 ... \times 10\times .... \times 25\times ... \times 50\times ... \times 250 ...\times 500\times .... \times n$

In [ ]:
 

We have a number that contributes at least one factor of 5 every 5 integers. That happens floor(n//5) times. But that undercount the total number of factors of 5, since every 25 integers, there is an extra factor of 5.

floor(n//5)+floor(n//25) still undercounts the extract factor that occur every 125 integers etc. So the final count is

floor(n//5) + floor(n//25) + floor(n//125) + floot(n//725) + ... + 0

Here is how we compute this fast:

In [2]:
def trailing_zeros(n):
    count = 0
    while n >= 5:
        n //= 5
        count += n
In [ ]:
We first add n//5 to count, then n//25 (n//5 twice), etc., to get the correctl result.
In [ ]:
 
In [ ]: