Tuesday, 20 August 2013

This programs takes a long time to close after the 'return;' on main()

This programs takes a long time to close after the 'return;' on main()

This is the code I am dealing with:
#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;
}
When I compile and run this program (using Visual Studio 2012 and Release
build settings) it takes like 10 seconds (on my computer) to close after
the program prints "Returning..."
Why is that?
Note: I am aware that this program is bad written and that i probably
shouldn't be using 'static' on the collatzLength nor using a cache for
that function, but I am not interesting on how to make this code better, I
am just interesting about why does it take so much to close.

No comments:

Post a Comment