项目Euler:#14整数溢出和堆栈溢出

时间:2011-07-20 10:55:43

标签: c++

unsigned long long terms;
unsigned 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;

超出INT_MAX,我该如何纠正?我尝试以递归方式使用Hash_map,但叠加。

1 个答案:

答案 0 :(得分:2)

这是Collatz Conjecture。考虑使用memoization通过存储您看到的链的长度来解决问题(例如,如果6给出链长为7,并且在处理更改N时遇到6,那么您可以添加7到链长到目前为止并立即返回)。