我找不到 Project Euler 问题 #14 的问题所在。我的第一步是找到算法,该算法一直有效,直到数字达到 120000 左右。代码中断并意识到我需要使用 BigIntegers。我转换了我的算法以适应这种变化,但现在它不起作用。
我添加了 System.out.print(chain_length) 来帮助我解决我的代码可能会中断的地方。
public static void main(String[] args) {
BigInteger target = new BigInteger("1000000");
BigInteger n = new BigInteger("0");
final BigInteger zero = new BigInteger("0");
final BigInteger one = new BigInteger("1");
final BigInteger two = new BigInteger("2");
final BigInteger three = new BigInteger("3");
final BigInteger ten = new BigInteger("10");
int greatest_index = 0;
int greatest_length = 0;
int chain_length = 0;
BigInteger i = new BigInteger("2");
for(i.equals(2) ; i.compareTo(target) == -1 ; i = i.add(one)) {
n = i;
chain_length = 1;
while(n.compareTo(one) == -1) {
chain_length++;
if(n.mod(ten).equals(zero) == true){//even
n = n.divide(two);
}else{//odd
n = n.multiply(three);
n = n.add(one);
}
if(n.equals(one) == true && chain_length > greatest_length){
greatest_length = chain_length;
greatest_index = i.intValue();
}
}
System.out.println(chain_length);
}
System.out.println(greatest_index);
}