看了一下网站,这个问题主要是要从到底有多少个因子5来得出结果。因为每个5与前面一个偶数相乘的话都能都到一个0!所以在求n!的时候,遍历n,分别看1~n中的每个数有多少个因子5,最后n!末尾就有多少个0.下面是代码:
#include<iostream>
using namespace std;
//n!后面有多少个零
int function(int n){
int count = 0;
for (int i = n; i >= 1; --i){
int j = i;
while (j % 5 == 0){
count++;
j = j / 5;
}
}
return count;
}
//求n!
int function2(int n){
if (n == 1)
return 1;
else{
return (n*function2(n - 1));
}
}
int main(){
cout << function2(10)<<","<<function(10) << endl;
return 0;
}
代码: