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
##AlgorithmcountTrailingZeros(n)begin count := 0 for i := 5, (n/i) >= 1, increase i := i * 5, do count := count + (n / i) done return count; end
#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); }
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!