I cannot find what's wrong for Project Euler problem #14. My first step was finding the algorithm, which worked until the numbers hit around 120000. The code broke and realized that I needed to use BigIntegers. I converted my algorithm to meet that change, but now it does not work.
I've added the System.out.print(chain_length) to assist me in where my code can potentially break.
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);
}
BigInteger
s,long
is enough.