Home > Backend Development > C++ > body text

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

PHPz
Release: 2023-09-20 22:05:09
forward
1367 people have browsed it

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

Calculating the number of trailing zeros in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 is equal to 10, and 10 is the last zero in the factorial number.

Example

The factorial of 7=5040, and the number of 0s at the end is 1.

According to our logic, 7!=2*3*4*5*6*7, which has 3 2s and 1 5, so the number of 0s at the end 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;
}
Copy after login

Output

No of trailing 0s in 24! is 10
Copy after login

The above is the detailed content of C/C++ programming 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