我的代码编译没有错误,但是在我的输出中我得到了第37行的ArrayOutofBoundsException。除了主计数器之外,一切都有效。任何人都可以看到我在这段代码中犯了什么错误?主要计数器在我的另一个程序中工作。
import java.util.Scanner;
public class Sieve {
public static void main(String[] args) {
//get ceiling on our prime numbers
int N;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the prime number ceiling: ");
N = sc.nextInt();
sc.close();
//init our numbers array, where true denotes prime
boolean[] isPrime = new boolean[N];
isPrime[0] = false;
for (int c = 1; c < N; c++) {
isPrime[c] = true;
}
//check every number >= 2 for primality
//first loops, checks to see is numbers are marked
for (int i = 2; i <= N; i++) {
if (isPrime[i-1]) {
System.out.print(i + " ");
//cross off all subsequent mutliples of
//second loop, marks all multiples of number
for (int j = i * 2; j <= N; j += i) {
isPrime[j-1] = false;
}
}
}
//counts primes
int primes = 0;
for (int c = 0; c <= N; c++) {
if (isPrime[c]); //error here
primes++;
}
//prints # of primes
System.out.println(" ");
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
答案 0 :(得分:1)
你的for循环条件不好
for (int c = 0; c <= N; c++) {
应该是
for (int c = 0; c < N; c++) {
因为你有一个维数N的数组,并且cointng从0开始。
for (int c = 1; c < N; c++) {
isPrime[c] = true;
}
此代码将所有数字设置为素数。 你应该做的是将每个数字设置为素数,然后将数字的每个倍数设置为不是素数。
所以就像
Arrays.fill(isPrime, true);
isPrime[0] = false;
for (int x = 1, x < N; x++) {
for (int y = x; y < N; y+=x) {
isPrime[y] = false;
}
}
这应该是真正的筛选算法。请参阅https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes