【发布时间】:2013-11-19 10:09:44
【问题描述】:
这是我执行 Sieve Of Eratosthenes 的函数,
void solve() throws IOException {
int n = 200000;
ArrayList<Integer> primes = new ArrayList<Integer>();
BitSet bs = new BitSet(n + 1);
for(int i = 0; i <= n + 1; i++)
bs.set(i);
//setting bits at 0 and 1 to 0, since these are not considered as primes
bs.clear(0);
bs.clear(1);
for(int i = 2; i <= n + 1; i++) {
if(bs.get(i)) {
//cross out multiples of i starting from i*i (lesser one would have always been crossed out)
for(int j = i*i; j <= n + 1; j += i)
{
bs.clear(j);
}
primes.add(i); //add this prime to the list
}
}
for(int e : primes)
out.println(e);
}
当我运行这个时,我在内部 for 循环中得到了 arrayOutOfBoundsException,即
for(int j = i*i; j <= n + 1; j += i)
{
bs.clear(j); //EXCEPTION is raised here
}
我得到的错误信息是:
Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -2146737495
at java.util.BitSet.clear(BitSet.java:532)
at ERATOSTHENES.solve(ERATOSTHENES.java:45)
我不明白问题出在哪里,如果我将 n 减少到 20000,那么我的代码可以正常工作,但是在 n = 168000(大约)之后,它会显示这个 OutofBoundsException。
它是 BitSet 特有的东西,我没有得到的一些属性吗?
【问题讨论】:
标签: java indexoutofboundsexception bitset sieve-of-eratosthenes