1

Question: Given an integer n, find the number of trailing zeroes in n!

I looked up the solution, it was implemented in C++:

// we are given n, we want to find its n! trailing zeroes

int count = 0;
while(n)
{
  count += n/5;
  n /= 5;
}
  return count;
}

I couldn't work my head around why I need to keep divide by 5, and then sum. Although this is a programming question, given its mathematical nature, I think it is more suitable for this forum because we have so many math genius here.

Please help me out.

randy
  • 533

1 Answers1

0

A trailing 0 means the number is divisible by 10, i.e. it is divisible by 2 and 5. The number of 0s at the end is the same as the highest power you could write for the 10 in a factorization of the number, or, the power on either the 2 or the 5 in the prime factorization (take the minimium on the two powers, e.g. if your factorization yields $2^4\cdot 5^3$ the number of $10$s you have is $3$, since you could rewrite it as $2^1\cdot 10^3$).

Since $n!$ is the product of all the numbers less than or equal to itself and $5>2$, the number of $5$s will never exceed the number of $2$s. Therefore, you only need the power on the $5$ in the prime factorization of $n!$

To find this, first see how many multiples of $5$ there are $\leq$ n. Then the number of multiples of $25$, and so on. The correct answer is given by the sum of all these values since each $5$ adds one to the power, each $25$ adds $2$, each $125$ adds $3$, and so on.

Consider $30!$

$5,10,15,20,25,30$ all contribute a factor of $5$ to $n!$

But $25$ contributes an extra $5$.

Therefore, the answer is $6+1=7$ zeros for $30!$.

rikhavshah
  • 1,355