java - Euler014 使用 int 比使用 long 花费的时间长得多

标签 java int

如果我运行下面的代码,只需不到 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 范围,所以它用 intlong< 循环了 很多/s。参见 my other answer here on Stack Overflow有关为什么 Euler014 在您使用的范围内(巧合的是其他提问者使用的范围)在 Java 上需要 long 的更详细解释。

使用更新后的变量名称引用该答案:

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.

因此您会长时间循环等待 sequencewhile 循环中返回到 1

关于java - Euler014 使用 int 比使用 long 花费的时间长得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17683128/

相关文章:

int - C# 3 字节整数

Java字节转int

python - 随机矩阵 : int() argument must be a string or a number, 不是 'tuple'

java - Android:如何使用 minifyEnabled 生成签名的 APK

java - 数组忽略 Null 作为值

integer - 用 byte 或 Short 模拟 int 变量

c# - 将 Int 转换为两个 Shorts 返回填充数据/负值

java - sqlite - 如何在Where子句中使用变量?

java - 包含 2 个下划线和 3 个段的文件名的正则表达式

Java 如何从字符串中解析微笑符号