开发者

Project Euler:#14 Integer overflow and Stack overflow

开发者 https://www.devze.com 2023-03-21 21:39 出处:网络
unsigned long long terms; uns开发者_开发知识库igned long long test; unsigned long long digit = 1;
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).

0

精彩评论

暂无评论...
验证码 换一张
取 消