简体   繁体   中英

Can someone tell me why I get this output?

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 (eg 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)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM