java - 为什么 Collat​​z 猜想程序不适用于 Java 中的大整数

标签 java math integer-overflow collatz

这是我在Java上模拟Collat​​z猜想的程序:

import java.util.*;
public class Collatz {
public static void main(String args[]){
    Scanner raj= new Scanner(System.in);
    int n;
    int k=0;
    System.out.print("n? ");
    n = raj.nextInt();
    while(n > 1){
        if(n%2 ==1){
            n=3*n+1;
            System.out.println(n);
            k++;
        }
        if(n%2==0){
            n=n/2;
            System.out.println(n);
            k++;
        }

    }
    System.out.print("It took " + k + " iterations!");
}

}

当我输入 n=6 时,我得到

3 10 5 16 8 4 2 1 It took 8 iterations!

但是当我输入 n=63728127 时,我得到

191184382 95592191 286776574 143388287 430164862 215082431 645247294 322623647 967870942 483935471 1451806414 725903207 -2117257674 -1058628837 It took 14 iterations!

出了什么问题?为什么?我该如何解决?谢谢!

最佳答案

这是一个经典的整数溢出案例。原始整数在 Java 中的范围有限。解决方案是始终使用类似 BigInteger 的东西如果您必须处理大整数。

顺便说一句,如果 Java 像几乎所有其他现代语言一样支持运算符重载,事情就会简单得多。

import java.util.*;
import java.math.BigInteger;


public class Collatz {
    public static void main(String args[]){
        Scanner raj= new Scanner(System.in);
        int k=0;
        System.out.print("n? ");

        BigInteger n = BigInteger.valueOf(raj.nextLong());

        while(n.compareTo(BigInteger.ONE) > 0){
            if(n.testBit(0)){
                n = n.multiply(BigInteger.valueOf(3));
                n = n.add(BigInteger.ONE);
                System.out.println(n);
                k++;
            }
            else {
                n = n.divide(BigInteger.valueOf(2));
                System.out.println(n);
                k++;
            }
        }
        System.out.print("It took " + k + " iterations!");
    }
}

关于java - 为什么 Collat​​z 猜想程序不适用于 Java 中的大整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920019/

相关文章:

java - for 循环的 while 部分在 java 中是每次执行一次还是只执行一次?

algorithm - ∀ y ∈ R+, ∃ z ∈ R, e^z = y 用伪代码怎么写?

javascript - 为什么 << 32 在 javascript 中不会导致 0?

java - 用于计算飞镖可能完成情况的递归函数

algorithm - 质因数分解

mips - mips 中的算术溢出

java - Java 如何处理整数下溢和上溢,您将如何检查它?

java - 如何使用WatchService观看多个目录?

java - 如果数据库调用来自多台机器,Spring 事务能否提供必要的互斥

javascript - 使用来自已加载网页的 JavaScript 调用重新加载 WebView