1、问题描述
输入一个正整数n,求n!(即阶乘)末尾有多少个0? 比如: n = 10; n! = 3628800,所以答案为2
输入描述:
输入为一行,n(1 ≤ n ≤ 1000)
输出描述:
输出一个整数,即题目所求
2、示例
输入
10
输出
2
3、问题解析
1)我的思路是求末尾0的个数就对末尾非0的几位数与新到来的数i进行乘积运算,计算新得出来的乘积中末尾为0的个数。比如说 计算10!的时候,9!=362880,那么就取末尾不为0的一位8,与10相乘,得到80,末尾多了一个0,计数器cnt就+1。这样的理论依据我也不清楚,在取1位的时候计算前1000个数是不对的,但是取到3位的时候(也就是(9!取288)),计算结果就正确了。。。。
下面是代码:
#include<iostream>
using namespace std;
int main() {
int n;
while (cin >> n) {
cin >> n;
int i = 1;
int cnt = 0;
int mul = 1, tmp = 1;
for (i = 1; i <= n; ++i) {
mul *= i;
tmp = mul;
while (!(tmp % 10)) {
cnt++;
tmp /= 10;
}
mul = tmp%1000;//取3位
}
cout << cnt << endl;
}
}
2)看了一下其他人的思路,末尾0的个数可以转换为求1~n中5以及5的倍数的个数,很巧妙,因为只有5的整数倍可以产生0
下面是代码:
//可以参考一下求某个数整数倍的数目的方法
#include<iostream>
#include<iomanip>
#include<string>
#include<vector>
using namespace std;
int main()
{
int n, counter=0;
cin >> n;
while (n/=5)
{
counter += n;
}
cout << counter;
return 0;
}