A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/count-trailing-zeros-in-factorial-of-a-number-in-cplusplus below:

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

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.

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
Kickstart Your Career

Get certified by completing the course

Get Started

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4