Published on

Trailing Zeros in Factorial

Authors

For any positive integer nn, the factorial of nn, denoted as n!n!, is defined as

n!=n×(n1)×(n2)×...×2×1.n!=n\times(n−1)\times(n−2)\times...\times2\times1.

0!0! is defined as 1, i.e. 0!=10!=1, though it looks unintutive. However, we can write this formula recursively as follows:

f(n)=f(n1)×nf(n)=f(n-1)\times n

f(0)=0f(0)=0

Now, for n=1n=1, we have 1!=1×0!1!=1\times 0! and this implies that 0!=10!=1.

The table below shows the values of the factorial for the integers 1 to 16.

nnn!n!
11
22
36
424
5120
6720
75040
840320
9362880
103628800
1139916800
12479001600
136227020800
1487178291200
151307674368000
1620922789888000

Counting the Trailing Zeros

How do we find the number of trailing zeros in a factorial? For example, when nn is 5, n!n! has 1 trailing zero; when nn is 12, n!n! has 2 trailing zeros; when nn is 16, n!n! has 3 trailing zeros.

Given a positive integer number nn, how many trailing zeroes are in nn factorial?

Bonus: can you implement this in any programming language?