Reputation: 87
I've stumbled on the following problem: I have a class to get and print all primes between 1 and N. The N is a parameter which you have to insert by yourself. When I insert 10000 for N, the code works and prints out all primes out from 2 to the closest prime to N.
When I insert 40000 the code still works. When I insert 50000 (or higher), the code gives an ArrayOutOfBoundsException. Why?
This is the code I use:
ArrayList<Integer> priemGetallen = priemGetallen(n);
for (Integer i : priemGetallen) {
System.out.println(i);
}
And uses
ArrayList<Integer> priemgetallen = new ArrayList<Integer>();
for(int i = 2; i < n; i++){
priemgetallen.add(i);
}
for (int i = 2; i < n; i++) {
for (int j = i; j * i <= n; j++) {
if((j*i) < priemgetallen.size()){
priemgetallen.remove(j*i);
}
}
}
return priemgetallen;
}
The point "priemgetallen.remove(j*i)" is where I receive the error.
I'd really appreciate it if someone can tell me why this doesn't work for all N's bigger then approx. 40000.
Thanks in advance!
Upvotes: 0
Views: 203
Reputation: 500177
The maximum value a Java int
can hold is 2,147,483,647, so j * i
is overflowing when i
and j
reach 46,341.
To extend the range, change the types of i
, j
and n
to long
.
See How does Java handle integer underflows and overflows and how would you check for it?
P.S. You'll also need to change priemgetallen
into an array list of Long
rather than Integer
.
Upvotes: 4