Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Count Trailing Zeros in Factorial of Number

$
0
0

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

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

10! = 3628800

So, trailing zeros = 2

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

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

 

Trailing zeros in n! = Count 5s in prime factors of 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 Zeros 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

Count Trailing Zeros in Factorial of Number

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

The post Count Trailing Zeros in Factorial of Number appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles