I need to generate a big table of primes (well, I could just download them I suppose - but do I trust some random Internet person to get it right?).
I wrote the following naive code:
EDIT: Riven suggestion highlighted.
public class FindPrimes {
public static void main(String[] args) {
++ List<Long> primes = new ArrayList<>(1000_000);
++ primes.add(2L);
++ long candidate = 3;
while (primes.size() < 1000_000) {
boolean isPrime = true;
for (long prime : primes) {
if (candidate % prime == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(candidate);
System.out.println(primes.size() + "\t: " + candidate);
}
++ candidate += 2;
}
}
}
I’ve looked up https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes, but I don’t see how that is going to be faster…
EDIT: I should of course set capacity of the ArrayList to 1000_000…