1

If I run the code below it takes less than 1 seconds to complete.

Bu if I change the sequence from long to int it takes more than 10 minutes.

Why?

long sequenceLength = 0;
long startingNumber = 0;
long sequence;

for (int i = 2; i <= 1000000; i++) {
    int length = 1;
    sequence = i;
    while (sequence != 1) {
        if ((sequence % 2) == 0) {
            sequence = sequence / 2;
        } else {
            sequence = sequence * 3 + 1;
        }
        length++;
    }

    //Check if sequence is the best solution
    if (length > sequenceLength) {
        sequenceLength = length;
        startingNumber = i;
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
b4da
  • 3,010
  • 4
  • 27
  • 34

2 Answers2

6

It's because you've overflowing the int range, and so it's looping a lot more with ints than longs. See my other answer here on Stack Overflow for a more detailed explanation of why Euler014 requires long on Java over the range you're using (which, coincidentally, is the range the other questioner was using).

Quoting from that answer with the updated variable name:

At one point in the chain, sequence is 827,370,449 and you follow the sequence = sequence * 3 + 1 branch. That value wants to be 2,482,111,348, but it overflows the capacity of int (which is 2,147,483,647 in the positive realm) and takes you to -1,812,855,948.

And so you keep looping for a long time waiting for sequence to come back around to 1 in your while loop.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

At a guess? I suspect the overflow behavior is different. If any intermediate result exceeds 2^31 - 1, then an int would overflow to a negative number, which would then have different results generally.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413