Project Euler:#14 Integer overflow and Stack overflow
unsigned long long terms;
uns开发者_开发知识库igned long long test;
unsigned long long digit = 1;
unsigned long long max = 0;
//cout<<sizeof(long)<<" "<<sizeof(int)<<endl;
//cout<<digit<<endl;
for(;digit<1000000;++digit)
{
terms = 1;
test = digit;
while(test>1)
{
if(0==(test%2))
{
test /=2;
}else{
test = test *3 +1;
}
terms ++;
}
if(terms>max)
max = terms;
}
//terms = get_chain_length();
/*if(terms>max)
max = terms;*/
//cout<<sizeof(long long)<<endl;
cout<<max<<endl;
It is out of INT_MAX, how can I correct it? I try to use Hash_map in a recursive way, but stack over.
This is the Collatz Conjecture. Consider using memoization to solve the problem by storing the lengths of the chains you've seen for (e.g. if 6 gives a chain length of 7 and you encounter 6 when processing change N, then you can just add 7 to the chain length so far and immediately return).
精彩评论