Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop stops running java

Tags:

java

For the code below, it stops running when "n" gets around 100,000. I need it to run until 1 million. I dont know where its going wrong, I am still learning Java so there might be simple mistakes in the code as well.

 public class Problem14{
public static void main(String[] args) {
    int chainLength;
    int longestChain = 0;
    int startingNumber = 0;
    for(int n =2; n<=1000000; n++)
    {
        chainLength = getChain(n);
        if(chainLength > longestChain)
        {
            System.out.println("chainLength: "+chainLength+" start: "+n);
            longestChain = chainLength;
            startingNumber = n;
        }
    }

    System.out.println("longest:"+longestChain +" "+"start:"+startingNumber);
}
public static int getChain(int y)
{
    int count = 0;
    while(y != 1)
    {
        if((y%2) == 0)
        {
            y = y/2;
        }
        else{
            y = (3*y) + 1;
        }
        count = count + 1;
    }

    return count;   
}
}
like image 292
stackErr Avatar asked Dec 16 '22 20:12

stackErr


2 Answers

Please use long as the data type instead of int

I will want this to come into light, that the number does flung higher than 1000000, so variable y needs long to hold it.

like image 188
Kumar Vivek Mitra Avatar answered Dec 18 '22 10:12

Kumar Vivek Mitra


It's the datatype for y. It should be long. Otherwise it wraps round to -2 billion.

I thought I recognised this - it's Euler problem 14. I've done this myself.

like image 45
Dan Avatar answered Dec 18 '22 10:12

Dan