Program to find trailing zeros in factorial of n in C++?

C++Server Side ProgrammingProgramming

Suppose we have a number n, we have to find the number of trailing zeros of n!.

So, if the input is like n = 20, then the output will be 4, as 20! = 2432902008176640000

To solve this, we will follow these steps

  • set count := 0

  • for i := 5, (n/i) > 1, update i := i * 5, do

    • count := count + (n /i)

  • return count

Let us see the following implementation to get better understanding

Example

 Live Demo

#include <iostream>
#include <cmath>
#define MAX 20
using namespace std;

int countTrailingZeros(int n) {
   int count = 0;

   for (int i = 5; n / i >= 1; i *= 5)
      count += n / i;

   return count;
}

main() {
   int n = 20;
   cout << "Number of trailing zeros: " << countTrailingZeros(n);
}

Input

20

Output

Number of trailing zeros: 4
raja
Published on 10-Nov-2020 09:24:02
Advertisements