0

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!

rgettman
  • 176,041
  • 30
  • 275
  • 357

1 Answers1

4

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • you would also have to change `priemgetallen.add(i);` to `priemgetallen.add((int)i);` since `List.add()` takes an int – dkatzel Oct 21 '14 at 15:38
  • @NPE Thank you! It all seems so logical when other people tell it, while it's quite hare to come up with by yourself. Have an invicible upvote. – Supermaniac Oct 21 '14 at 18:17