这是我正在处理的代码:
#include <iostream>
#include <map>
using namespace std;
static unsigned long collatzLength(unsigned long n) {
static std::map<unsigned long,int> collatzMap;
int mapResult = collatzMap[n];
if (mapResult != 0) return mapResult;
if (n == 1) {
return 1;
} else {
collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
return collatzMap[n];
}
}
int main() {
int maxIndex = 1;
unsigned int max = 1;
for (int i=1; i<1000000; i++) {
//cout<<i<<endl;
unsigned long count = collatzLength(i);
if (count > max) {
maxIndex = i;
max = count;
}
}
cout<<maxIndex<<endl;
getchar();
cout<<"Returning..."<<endl;
return maxIndex;
}
当我编译并运行这个程序(使用 Visual Studio 2012 和 Release 构建设置)时,在程序打印“Returning...”后需要大约 10 秒(在我的计算机上)关闭
这是为什么?
注意:我知道这个程序写得不好,我可能不应该在 collatzLength 上使用“静态”,也不应该为该函数使用缓存,但我对如何使这段代码更好并不感兴趣,我只是有趣的是为什么要花这么多时间才能关闭。