I was solving Project Euler problem 10 and I was able to do so using the Sieve of Eratosthenes, but now I'd like to optimize the code a bit further.
Considering the fact that all prime numbers greater than 3 are of the form 6k+1 or 6k-1 I only set those values in the array as true, but not all numbers of that form will be prime, so I have to sieve through the values and remove the non primes, and my code is as follows:
public static bool[] GeneratePrimes(int bound)
{
bool[] isPrime = new bool[bound];
isPrime[2] = true;
isPrime[3] = true;
// Taking into account that all primes greater than 2 and 3
// Are of the form 6k+1 or 6k-1
for (int k = 6; k < isPrime.Length; k += 6)
{
if (k + 1 < isPrime.Length) isPrime[k + 1] = true;
isPrime[k - 1] = true;
}
// At this point we still have some numbers that aren't prime marked as prime
// So we go over them with a sieve, also we can start at 3 for obvious reasons
for (int i = 3; i * i <= bound; i += 2)
{
if (isPrime[i])
{
// Can this be optimized?
for (int j = i; j * i <= bound; j++)
isPrime[i * j] = false;
}
}
return isPrime;
}
}
So how can I optimize the code that I sieve through less numbers? For example if my number is 5, numbers such as 10,15,20 are already stroked through, but 25 for example isn't so is it possible to only go through values such is 25?