为什么Collatz猜想程序在Java中不能处理大整数
这是我在Java上模拟Collatz猜想的一个程序:为什么Collatz猜想程序在Java中不能处理大整数,java,math,integer-overflow,collatz,Java,Math,Integer Overflow,Collatz,这是我在Java上模拟Collatz猜想的一个程序: 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){
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时,我得到
三,
10
5.
16
8.
4.
2.
1.
它花了8次迭代
但是当我把n=63728127,我得到
191184382
95592191
286776574
143388287
430164862
215082431
645247294
322623647
967870942
483935471
1451806414
725903207
-2117257674
-1058628837
它花了14次迭代
出了什么问题?为什么?我怎样才能修好它?谢谢 这是整数溢出的典型情况。原语int在Java中的范围有限。解决方案是始终使用类似if的方法来处理大整数 顺便说一句,如果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!");
}
}
这是整数溢出的典型情况。原语int在Java中的范围有限。解决方案是始终使用类似if的方法来处理大整数 顺便说一句,如果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!");
}
}
那么我该如何编辑程序来使用这个BigInteger类呢?我不知道如何实现它,那么我该如何编辑程序来使用这个BigInteger类呢?我不知道如何实施它