Count Trailing Zeros in Factorial of Number

Here you will learn about how to count trailing zeroes in factorial of number.

One simple approach to count trailing zeroes is first find factorial of number and then count the zeroes in the factorial one by one. It is fine for smaller number like 10.

10! = 3628800

So, trailing zeroes = 2

But what about big numbers like 100. The factorial of 100 has 24 zeroes in the end and almost 160 digits. Its really hard to store that big number and then count the zeroes one by one.

There is a simple and very fast method to do this. We can count the zeroes by counting the 5s in prime factor of n factorial.

`Trailingzeroesin n! = Count 5s in primefactorsof n! = floor(n/5) + floor(n/25) + floor(n/125) + . . . . `

It is very frequently asked question in competitive programming. Let us see how this method can be implemented in C.

C Program to Count Trailing Zeroes in Factorial of Number

`#include<stdio.h>   int main(){     int i,n,count=0;          printf("Enter a number:");     scanf("%d",&n);          //repeatedly divide n by powers of 5 and update count     for(i=5;n/i>=1;i*=5){         count+=n/i;     }         printf("Trailing Zeroes=%d",count);     return 0; } `

Output

If you have any doubts regarding above tutorial then comment below.