14 - 欧拉计划 - Java - 错误答案 - 错误?

14 - Project Euler - Java - Incorrect Answer - Bug?

我找不到这段代码中的错误。如果不是欧拉计划判定我的答案不正确,我向天发誓我的代码是正确的。

我可以使用另一种方法,但这个问题并没有那么复杂,但我在寻找错误时完全失败了。

问题是:

为正整数集定义了以下迭代序列:

n → n/2(n 为偶数) n → 3n + 1(n 为奇数)

使用上面的规则并从 13 开始,我们生成以下序列:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 可以看出,这个序列(从 13 开始到 1 结束)包含 10 个项。虽然还没有证明(Collat​​z Problem),但是认为所有的起始数字都以1结束。

哪个起始数(小于一百万)产生最长的链?

我的代码是:

public class CollatzSequence014 {

public static void main(String [] args){
    long start = System.currentTimeMillis();
    long maxTotal = 0;
    long inputNum = 0;

        for (long i = 3; i < 1000000 ; i++){
            long total = generateSequence(i);
            if (total > maxTotal){
                inputNum = i;
                maxTotal = total;
            }
        }
    long end = System.currentTimeMillis();

    System.out.println("The input number was : " + inputNum + " and the total was " + maxTotal);
    System.out.println("Time taken : " + (end - start) + "ms");
}



public static long generateSequence(long n){
    long counter = 0;
    long currentDigit = n;

    while (currentDigit > 1){
        counter++;
        if (n % 2 == 0){
             currentDigit = currentDigit / 2;
        }
        else {
            currentDigit = (3 * currentDigit) + 1;
        }
    }
    return counter;
}

}

首先,你应该如何寻找错误:尝试输出小 n 的序列(不仅仅是长度)(例如 13,因为问题已经为你提供了正确的序列).您会看到您得到 1340121...,这应该已经告诉您错误在哪里。

您必须检查 currentDigit 是否为偶数,而不是 n

if(currentDigit % 2 == 0)

错误在这里:

if (n % 2 == 0){

应该是:

if (currentDigit % 2 == 0){