我试图解决今天上午的Codeforces问题分区2C:http://codeforces.com/contest/716/problem/Cint打破我for循环的最大值?
此问题有可能循环高达100,000次,因此这里的参数可能高达100,000。循环似乎打破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 IS高于最大整数限制,但是这个值永远不会在我的代码中存储为int。这里发生了什么?
如果需要更大的'int'类型,可以考虑使用'long',或['BigInteger'](https://docs.oracle.com/javase/7/ docs/api/java/math/BigInteger.html) – 4castle