![](/img/trans.png)
[英]ArrayIndexOutOfBoundsException while implementing Sieve of Eratosthenes
[英]Sieve of Eratosthenes, ArrayIndexOutOfBoundsException, output is composite number
我嘗試編寫Eratosthenes算法的篩網,但遇到ArrayIndexOutOfBoundsException,但我似乎不明白為什么,如果更改限制,在打印時僅顯示復合數字,如果可以的話,下面的代碼會有所幫助。
public static Boolean[] solution(int N) {
Boolean[] isPrime = new Boolean[N];
isPrime[0] = false;
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for(int i = 2; i <= N; i++) {
if(isPrime[i]== true) {
System.out.println(i);
for(int j = 2; (j * i) < N; j++) {
int k = j * i;
isPrime[k] = false;
}
}
}
return isPrime;
i <= N;
導致錯誤
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
例如
如果N=4
則當i=4
時會出錯。 OutOfBounds
isPrime[4]
導致OutOfBounds
異常,因為長度為4。數組基於零索引。 因此,您可以訪問的最大索引為isPrime[3]
您可以通過將循環更改為for(int i = 1; i < N; i++) {
但是我不確定什么是Eratosthenes算法。我希望您可以更改代碼,但要記住數組是基於零索引的
Boolean[N]
創建一個由N個元素組成的數組,因此,由於索引從0開始,因此最后一個索引為N-1。 該錯誤是由for循環中的i<=N
引起的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.