有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有人能告诉我为什么我会得到这个输出吗?

好的,我有一个Collatz序列长度,由以下代码定义:

    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;
    }

现在,我检查了输出(例如打印(collatz(3000))=>;48)以验证算法是否正确工作。我用various sites来做这件事,但有一个数字不起作用。这个数字正是欧拉投影上第14个问题的解。这是怎么可能的呢?我每隔一个数字就得到正确的结果(正确的链长),而837799产生一个不同的结果:58,而不是524


共 (1) 个答案

  1. # 1 楼答案

    正如其他人在评论中指出的,这是一个溢出问题。您可以通过打印函数调用的参数来发现这一点

    int更改为long,或者更好,为了确保它不会溢出,请使用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)));
    }