C/C++ Programming to Count trailing zeroes in factorial of a number?


Counting the number of trailing zeroes in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 gives 10 which is a trailing 0 in the factorial of a number.

Example

Factorial of 7 = 5040, the number of trailing 0’s is 1.

Based on our logic 7! = 2*3*4*5*6*7, it has 3 2s and 1 5s so the number of trailing 0’s is 1.

#include <iostream>
using namespace std;
int main() {
   int n = 45;
   int count = 0;
   for (int i = 5; n / i >= 1; i *= 5)
      count += n / i;
   cout<<"No of trailing 0s in " << n<< "! is " << count;
   return 0;
}

Output

No of trailing 0s in 24! is 10

Updated on: 08-Aug-2019

726 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements