如果我运行下面的代码,只需不到 1 秒即可完成。
但是,如果我将序列从 long 更改为 int,则需要 10 多分钟。
为什么?
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;
}
}