문제

Ok, so I have a Collatz sequence length defined by the following code:

    private static int count = 0;

    private static int collatz(int n){
        count++;
        if(n > 1){
            if(n % 2 == 0){
                return collatz(n/2);
            }
            return collatz(3*n+1);
        }
        return count-1;
    }

Now, I checked the output (e.g. print(collatz(3000)) => 48) of different numbers to verify if the algorithm works correctly. I used various sites to do this, yet one number refuses to work. And that number is exactly the solution of the 14th problem on ProjectEuler. How is this possible, that with every other number I get the right result (the correct chain length) while 837799 produces a different result: 58, instead of 524.

도움이 되었습니까?

해결책

As other pointed out in the comments, this is an overflow problem. You could have spotted this by printing the argument of the function call.

Change int to long, or even better, to be absolutely sure it does not overflow, use BigInteger:

private static int collatz(BigInteger n) {
    count++;
    if (n.compareTo(BigInteger.ONE) > 0) {
        if (!n.testBit(0)) // even
            return collatz(n.divide(BigInteger.valueOf(2)));

        else
            return collatz(n.multiply(BigInteger.valueOf(3)).add(BigInteger.ONE));
    }
    return count - 1;
}

public static void main(String[] args) {
    System.out.println("res: " + collatz(BigInteger.valueOf(837799)));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top