int 的最大值打破了我的 for 循环?

Maximum value of int breaking my for loop?

我试图解决今天早上的 Codeforces 问题 Div 2C:http://codeforces.com/contest/716/problem/C

这道题最多可以循环10万次,所以这里的参数最多可以设置为10万次。当传入 100,000(可能更早)并且 i 被声明为 int 时,循环似乎中断:

       public void solve(int a) {
        double x = 2;
        double y = 0;
        double n = 0;
        double target = 0;
        double lcm = 0;
        for (int i = 1; i <= a; i++) {
            lcm = (i + 1) * i; 
            y = ((lcm * lcm) - x) / i;
            n = (y * i) + x;
            if (Math.sqrt(n) % (i + 1) == 0) {
                x = Math.sqrt(n);
                String answer = String.format("%.0f", y);

                System.out.println("this is i: " + i);
                System.out.println(answer);

            }
        }
    }

这里是相关的输出:

this is i: 46337
99495281029892
this is i: 46338
99501722706961
this is i: 46340
99514606895203
this is i: 65535
32769

快速搜索堆栈溢出显示数字 65535 与 16 位无符号整数相关联,但 java 使用 32 位整数。将类型更改为 double 有效,就像简单地循环 100,000 次并在没有代码逻辑的情况下打印一样。我知道 100,000^2 高于最大 int 限制,但此值从未在我的代码中存储为 int。这是怎么回事?

在将结果转换为 double 之前,以下行生成越界 int

lcm = (i + 1) * i;

以上基本相同:

lcm = (double)((i + 1) * i);

int temp = (i + 1) * i;
lcm = (double) temp;

改为尝试(首先转换为双精度然后取类似于正方形的东西):

lcm = (i + 1.0) * i;