我正尝试通过www.spoj.com解决此问题:FCTRL-阶乘
您真的不必阅读它,如果您好奇的话就去做:)
首先,我用C ++实现了它(这是我的解决方案):
#include <iostream>
using namespace std;
int main() {
unsigned int num_of_inputs;
unsigned int fact_num;
unsigned int num_of_trailing_zeros;
std::ios_base::sync_with_stdio(false); // turn off synchronization with the C library’s stdio buffers (from https://stackoverflow.com/a/22225421/5218277)
cin >> num_of_inputs;
while (num_of_inputs--)
{
cin >> fact_num;
num_of_trailing_zeros = 0;
for (unsigned int fives = 5; fives <= fact_num; fives *= 5)
num_of_trailing_zeros += fact_num/fives;
cout << num_of_trailing_zeros << "\n";
}
return 0;
}
我将其上传为g ++ 5.1的解决方案
但是后来我看到一些评论,声称它们的时间执行少于0.1。由于我想不出更快的算法,因此尝试在C中实现相同的代码:
#include <stdio.h>
int main() {
unsigned int num_of_inputs;
unsigned int fact_num;
unsigned int num_of_trailing_zeros;
scanf("%d", &num_of_inputs);
while (num_of_inputs--)
{
scanf("%d", &fact_num);
num_of_trailing_zeros = 0;
for (unsigned int fives = 5; fives <= fact_num; fives *= 5)
num_of_trailing_zeros += fact_num/fives;
printf("%d", num_of_trailing_zeros);
printf("%s","\n");
}
return 0;
}
我将其上传为gcc 5.1的解决方案
现在,代码几乎相同,我std::ios_base::sync_with_stdio(false);
按照此处的建议将其添加到C ++代码中,以关闭与C库的stdio缓冲区的同步。我也拆printf("%d\n", num_of_trailing_zeros);
到printf("%d", num_of_trailing_zeros); printf("%s","\n");
以补偿的双呼叫operator<<
在cout << num_of_trailing_zeros << "\n";
。
但是我仍然看到C与C ++代码相比x9的性能更好,内存使用更低。
这是为什么?
编辑
我固定unsigned long
到unsigned int
在C代码。应该是这样unsigned int
,上面显示的结果与新(unsigned int
)版本有关。