KajitiSouls Wrote:Oops, my bad, I forgot the "== 1" part >.<
I decided to run the script again using a new isPrime method (while doing some college work), and the time was roughly the same o.O Hmm...
That's not to say I'm blaming anyone though. It just means that the majority of the time is being spent on comparing sets of primes with nextPrime.
Code:private static boolean isPrime(long n){
if(n <= 2) return false;
if(n % 5 == 0) return false;
int i = 0;
int squareRoot = (int) Math.sqrt(n);
for(i = 0; i < primesList.size() && primesList.get(i) <= squareRoot; i++){
if(n % primesList.get(i) == 0) return false;
}
//this for loop is necessary because sqrt(n) early on is usually larger than the largest prime in primesList.
if(primesList.get(primesList.size() - 1) <= squareRoot){
for(long j = primesList.get(primesList.size() - 1) + 2; j <= Math.sqrt(n); j += 2){
if(n % j == 0) return false;
}
}
return true;
}
This would be, more or less, the best way to use the Sieve for the purposes of this problem, no?
Yeah, that works. When initiating the prime-list, you can loop like this (pseudo):
Code:
loop for x = 5 then x + 6
if (isPrime(x))
add x in sieve
if (isPrime(x+2))
add x+2 in sieveAdd in 3 and remove 5, and you'll be fine. This will, most likely, increase the prime-checking part quite a lot. Whether that increases overall runtime by much or not, depends on the time it takes to run the other parts of the algorithm.

