我正試圖解決在任意自然數的階乘結束時計算0的標準問題。我的代碼工作正常,但網上裁判給出了「超時限」錯誤。決定在這裏問我如何優化我的代碼。C++:在最後優化計數零點
#include <iostream>
using namespace std;
int count (int n)
{
int result = 0;
for (unsigned int i = 5; i <= n; i += 5)
{
int temp = i;
while (!(temp % 5))
{
++result;
temp /= 5;
}
}
return result;
}
int main()
{
int N;
cin >> N;
cin.get();
for (unsigned int i = 0; i < N; ++i)
{
int n;
cin >> n;
cin.get();
cout << count (n) << endl;
}
return 0;
}
在此先感謝。
也許你需要的東西,如http: //stackoverflow.com/questions/11889999/c-number-of-zeros-in-a-factorial-number#? – Kupto
您正在將unsigned int分配給int。將所有整數更改爲提示 – user1596193
是否真的比將int或unsigned int分配給unsigned int需要更多時間,例如? –