I've been working at Problem 03 of Project Euler as a Java novice. (Find the largest prime factor of 600851475143.) It was my first time using ArrayLists and a few confusions came up - hopefully these can be cleared up!
public static ArrayList<Integer> primeList (int n){
ArrayList<Integer> prime = new ArrayList<Integer> ();
for (int i = 2; i <= n; i++) {
prime.add(i);
}
// Sieb des Eratosthenes
for (int i = 2; i <= Math.sqrt(n); i++) {
for (Integer j : prime) {
if (j > i && j % i == 0) {
prime.remove (Integer.valueOf(j)); // some error.
}
}
}
return prime;
}
This is my code for the Sieve of Eratosthenes. It's likely not very optimal, I know that - I will still continue to work on optimizing my algorithm.
However, what really bothers me is that this one doesn't compile. Somehow, it does compile for n = 2, 3, 5. For most other values I've tried, it does not.
Why is that? And more specifically, where is the error?
I was able to make it run with a "normal" for-loop instead of the for each-loop. That was a happy end, at least, I guess.
EDIT: By evaluating it in a main with Sys.out(primeList(9))
, I get the error message:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:907)
at java.util.ArrayList$Itr.next(ArrayList.java:857)
at problem03.TestPrime.primeList(TestPrime.java:18)
at problem03.TestPrime.main(TestPrime.java:7)