给定整数n,编写一个函数,返回n!中尾随零的计数。
例子 :
Input: n = 5
Output: 1
Factorial of 5 is 120 which has one trailing 0.
Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.
Input: n = 100
Output: 24
Trailing 0s in n! = Count of 5s in prime factors of n!
= floor(n/5) + floor(n/25) + floor(n/125) + ....
C++
// C++ program to count
// trailing 0s in n!
#include
using namespace std;
// Function to return trailing
// 0s in factorial of n
int findTrailingZeros(int n)
{
// Initialize result
int count = 0;
// Keep dividing n by powers of
// 5 and update count
for (int i = 5; n / i >= 1; i *= 5)
count += n / i;
return count;
}
// Driver Code
int main()
{
int n = 100;
cout << "Count of trailing 0s in " << 100
<< "! is " << findTrailingZeros(n);
return 0;
}
输出:
Count of trailing 0s in 100! is 24
有关更多详细信息,请参阅完整的关于计数因数的尾随零的文章!
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。