Home  >  Article  >  Backend Development  >  C/C++ program to calculate the number of trailing zeros in the factorial of a number

C/C++ program to calculate the number of trailing zeros in the factorial of a number

WBOY
WBOYforward
2023-08-29 12:29:051398browse

Here we will see how to calculate the number of trailing 0s in the factorial result of any number. So if n = 5, then 5! =120. There is only one trailing 0. For 20!, it would be 4 zeros as 20! = 2432902008176640000.

The simplest way is to calculate the factorial and calculate 0. But for larger values ​​of n, this approach fails. So we're going to take another approach. If the prime factors are 2 and 5, then trailing zeros will appear. If we calculate 2 and 5, we get the result. To do this we will follow this rule.

Trailing 0 = Count of 5 in factorial(n) prime factors

C/C++ program to calculate the number of trailing zeros in the factorial of a number

##Algorithm

countTrailingZeros(n)

begin
   count := 0
   for i := 5, (n/i) >= 1, increase i := i * 5, do
      count := count + (n / i)
   done
   return count;
end
## The Chinese translation of #Example

is:

Example

#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);
}

Output

Number of trailing zeros: 4

The above is the detailed content of C/C++ program to calculate the number of trailing zeros in the factorial of a number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete