Count trailing zeros in factorial of a number in C++



Given an integer number as input. The goal is to find the number of trailing zeroes in the factorial calculated for that number. A factorial of a number N is a product of all numbers in the range [1, N].

We know that we get a trailing zero only if the number is multiple of 10 or has a factor pair (2,5). In all factorials of any number greater than 5, we have a number of 2s more than 5s in prime factorization of that number. Dividing a number by powers of 5 will give us the count of 5s in its factors. So, the number of 5s will tell us the number of trailing zeroes.

For Example

Input

number=6

Output

Count of trailing zeros in factorial of a number are: 1

Explanation

The factorial is 30. Prime factors of 30 : 2 * 3 * 5 So only one pair of (2,5) exists so trailing zeros is 1.

Input

number=12

Output

Count of trailing zeros in factorial of a number are: 2

Explanation

The factorial is 479001600. Prime factors of 479001600 : 210 x 35 x 52 x 71 x 111 So we can get 2 pairs of (2,5) so trailing zeros are 2

Approach used in the below program is as follows

In this approach we will divide the number by powers of 5. If it results in more than 1 then the number of trailing zeros will be the number of 5s. Add this to count.

  • Take an integer number as input.

  • Function trailing_zeros(int number) takes number and returns the count of trailing zeroes in factorial of number.

  • Take the initial count as 0.

  • Using a for loop, divide the number by powers of 5.

  • If number/i is greater than 1, add this value to count.

  • Return count as result at the end of loop.

Example

 Live Demo

#include <iostream> using namespace std; int trailing_zeros(int number){    int count = 0;    for (int i = 5; number / i >= 1; i *= 5){       int temp = number / i;       count = count + temp;    }    return count; } int main(){    int number = 50;    cout<<"Count of trailing zeros in factorial of a number are: "<<trailing_zeros(number);    return 0; }

Output

If we run the above code it will generate the following output −

Count of trailing zeros in factorial of a number are: 12
Updated on: 2021-01-05T06:09:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements