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

时间:2016-09-17 23:15:03

标签: java loops int unsigned 16-bit

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

此问题有可能循环达100,000次,因此此处的参数最多可达100,000。在传递100,000(可能更早)时,循环似乎会中断,并且我被声明为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 IS高于最大int限制,但是这个值永远不会作为int存储在我的代码中。这是怎么回事?

1 个答案:

答案 0 :(得分:0)

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

lcm = (i + 1) * i;

以上基本相同:

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

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

而是尝试(首先转换为双倍然后采用类似于正方形的东西):

lcm = (i + 1.0) * i;