Reputation:
I tried writing a Sieve of Eratosthenes algorithm, I am getting an ArrayIndexOutOfBoundsException but I don't seem to understand why, if I change the limits, upon printing it only displays composite numbers, the code's below help if you can.
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;
Upvotes: 1
Views: 65
Reputation: 146
Boolean[N]
creates an array of N elements, so, since the indexes start from 0, the last index is N-1.
The error is caused by i<=N
in the for loop
Upvotes: 1
Reputation: 9880
i <= N;
cause the error
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for example
if N=4
then you get error when i=4
. isPrime[4]
cause OutOfBounds
exception because length is 4.arrays are zero index based. so maximum index you can access is 3.isPrime[3]
you can avoid this error by changing loop to for(int i = 1; i < N; i++) {
however i'm not sure what is Eratosthenes algorithem is .i hope you can change your code keep in mind arrays are zero index based
Upvotes: 1