Count trailing zeroes in factorial of a number

      No Comments on Count trailing zeroes in factorial of a number

Count trailing zeroes in factorial of a number – Given an integer ‘n’ , we need to calculate number of zeroes in the factorial of that number.

Examples:

Input n = 5
Output = 1
Factorial of 5 = 20which has 1 trailing zero.

Input n = 100
Output = 24

Count trailing zeroes in factorial of a number

One simple method to do this to calculate the factorial of the number and then count the trailing zeroes in the result.This method can result in overflow sometimes when the value is very large.

The other simple method is that, we count the number of 5 is the prime factor of n!

 number of trailing zeroes = count of 5s in prime factor of n!
                           = floor(n/5)+floor(n/25)+floor(n/125)...

Implementing this logic in C

#include<stdio.h>
int countTrailingzeroes(int n)
{
	int t=5,count=0;
	do
	{
		count+=n/t;
		t=t*5;
	}
	while(t<=n);
	return count;
}

int main()
{
	int n;
	printf("Enter number to calculate trailing zeroes \n");
	scanf("%d",&n);
	printf("Count of trailing zeroes is : \n");
	printf("%d",countTrailingzeroes(n));
}

Output:

Count trailing zeroes in factorial of a number

Summary
Count trailing zeroes in factorial of a number
Article Name
Count trailing zeroes in factorial of a number
Description
Count trailing zeroes in factorial of a number - Given an integer 'n' , we need to calculate number of zeroes in the factorial of that number.
Author
Publisher Name
Scanfcode
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *