如果我运行下面的代码,只需不到 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;
}
}
最佳答案
这是因为你已经溢出了 int
范围,所以它用 int
比 long< 循环了 很多/
s。参见 my other answer here on Stack Overflow有关为什么 Euler014 在您使用的范围内(巧合的是其他提问者使用的范围)在 Java 上需要 long
的更详细解释。
使用更新后的变量名称引用该答案:
At one point in the chain,
sequence
is827,370,449
and you follow thesequence = sequence * 3 + 1
branch. That value wants to be2,482,111,348
, but it overflows the capacity ofint
(which is2,147,483,647
in the positive realm) and takes you to-1,812,855,948
.
因此您会长时间循环等待 sequence
在 while
循环中返回到 1
。
关于java - Euler014 使用 int 比使用 long 花费的时间长得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17683128/