Java: ArrayOutofBounds Exception when trying to count primes using Sieve

130 Views Asked by At

My code compiles without errors, but the in my output I'm getting an ArrayOutofBoundsException for line 37. Everything works except the prime counter. Can anyone see where I made a mistake in this code? The prime counter works in another program I have.

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);
}
}
1

There are 1 best solutions below

2
On BEST ANSWER

Your for loop condition is bad

for (int c = 0; c <= N; c++) {

should be

for (int c = 0; c < N; c++) {

as you have an array of dimension N, and the cointng starts from 0.


for (int c = 1; c < N; c++) {
        isPrime[c] = true;

}

This code sets all numbers to be primes. What you should do is setting every number to be prime, and later setting every multiple of a number to not be prime.

so it would be like

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;
   }
}

This should be the real sieve algorithm. Refer to https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes