题目
求出100的阶乘最后连续0的个数;
思路
主要是计算1-100这些数字中有几个5的问题,因为若要末尾产生0;则想成的两位数必然可以分解成(2,5)对,所以只需要计算有几个5就行
//100里面有5,10,15,20...100;共有20个;
//25=5*5,50=5*5*2,75=5*5*3,100=5*5*4
代码
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int count(int n);
int main()
{
int tmp = 100;
cout << tmp << "有" << count(tmp) << "个0" << endl;
}
int count(int n)
{
int num = 0;
for (int i = 5; i <= n; i++) {
if (i % 5 == 0) {
num++;
if (i % (5 * 5) == 0)
num++;
}
}
return num;
}
结果
若要计算N的阶乘末尾有几个0呢?
代码:
#include <iostream>
using namespace std;
int main()
{
int n, k, sum;
cin >> n;
sum = 0;
k = n;
while (n)
{
n /= 5;
sum += n;
}
cout << sum << endl;
return 0;
}
运行结果:
第一行表述输入的n;第二行输出末尾0的个数。
思路:
100/5 = 20;
20/5 = 4;
4/5 = 0;
跳出循环。