试图解决项目euler 14号

时间:2015-09-24 15:27:54

标签: c++

我正在尝试解决项目euler问题14号,我的代码几乎准备就绪,但它让我给出了错误的答案..为什么它不计算更多的步骤?谢谢,抱歉缺乏评论..

#include <iostream>

int collatz_length(int number);

int main() {
    using namespace std;

    int size_sequence, max_sequence = 0, number_ = 1000000, num;

    while (number_>1) {
        size_sequence = collatz_length(number_);
        if (size_sequence > max_sequence) {
            max_sequence = size_sequence;
            num = number_;
            cout << "size   " << size_sequence 
                << "   starting number   " << num << endl;

        }
        number_--;
    }
    cout << "The longest sequence has "
        << max_sequence << " steps, starting from the number: "  << num << endl;
    cin.get();
    return 0;
}

int collatz_length(int number) {
    using namespace std;

    int size_sequence = 0;

    while (number > 1) {
        if ((number % 2) == 0){
            number /= 2;
        }
        else {
            number = (3 * number + 1);
        }
        size_sequence++;
    }

    return size_sequence;
}

1 个答案:

答案 0 :(得分:1)

3*n+1可能会溢出int。也许您应该使用uint64_t