未解之谜(第一个Java程序)
看了一下自己的博客,访问量最多的居然是未解之谜,其实没花什么功夫就写成了,可见角谷猜想有许多人关注。正好最近在学Java,就试着写了一个类似程序。一开始是这样的:
package test;
import java.util.Scanner;
public class mystery {
public static void main(String[] args) {
// TODO Auto-generated method stub
long n;
Scanner input = new Scanner(System.in);
n = input.nextLong();
while (n!=1) {
if (n%2==0) {
n=n/2;
}
else {
n=3*n+1;
}
System.out.println(n);
}
}
}
但这个程序的问题是,当n超过long的范围(大于9223372036854775807),就会报错。所以想想Python,真的是太人性化了,太好用了。
怎么解决?查了一下资料,导入BigInteger类,可以解决这个问题。
BigInteger有多种运算方法,加、减、乘、除、位移、取商取余等都没有问题。使用方法与Python的decimal有类似的地方,是接受字符串的。程序看下来怪怪的,效果却是杠杠的。
注意,在进行比较的时候,不能使用(==,!=等),不然会报错。
package test;
import java.math.BigInteger;
import java.util.Scanner;
public class Biginteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String n = input.nextLine();
BigInteger big = new BigInteger(n);
while (true) {
if (big.remainder(new BigInteger("2")).equals(new BigInteger("0"))) {
big = big.divide(new BigInteger("2"));
}
else {
big = big.multiply(new BigInteger("3")).add(new BigInteger("1"));
}
System.out.println(big);
if (big.equals(new BigInteger("1"))){
break;
}
}
}
}