Home > Backend Development > C++ > 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
Release: 2023-08-29 12:29:05
forward
1484 people have browsed it

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

Output

Number of trailing zeros: 4
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template