Java:Project Euler#14错误答案

时间:2013-12-15 17:16:11

标签: java

Project Euler中的Problem 14代码给出了错误的答案,我看不出有什么问题。这是我的代码

public static void main(String[] args) {
        long answer = 0;
        long longest = 0;
        for (long i = 0; i < 1000000; i++) {
            long num = i;
            long counter = 1;
            while (num > 1) {
                if (num % 2 == 0) num /= 2;
                else num = 3 * num + 1;
                counter++;
            }
            if (counter > answer) {
                answer = i;
                longest = counter;
            }
        }
        System.out.println(answer);
        System.out.println(longest);
    }

1 个答案:

答案 0 :(得分:2)

您将链的长度与产生链的数量进行比较。

if (counter > answer) {
    answer = i;
    longest = counter;
}

应该是:

if (counter > longest) {
    answer = i;
    longest = counter;
}