I've been on a Project Euler spree and I've been solving problems and as you might know, many of them require you to use prime numbers. I've been using the following code to generate and store primes in a vector, but was wondering if there is any non-obvious speed-ups that will make a large difference on the runtime of the generation.
// Generate the primes upto N using the Sieve of Eratosthenes.
template<typename T>
std::vector<T> generatePrimes(T n) {
std::vector<T> result = std::vector<T>();
if(n < 2) {
return result;
}
std::vector<int> input(n + 1, 1);
// Calculates the upper limit of the numbers to check.
T sqrtN = (T)sqrt(n);
// Iterate till the square root.
for(T i = 2; i <= sqrtN; i++) {
if(!input[i]) {
continue;
}
// Multiples are marked false.
for(T j = i * i; j <= n; j += i) {
input[j] = 0;
}
}
// Add to result vector.
result.push_back(2);
for(T i = 3; i <= n; i += 2) {
if(input[i]) {
result.push_back(i);
}
}
return result;
}
And it is called like so:
vector<unsigned int> primes = generatePrimes<unsigned int>(10'000);
Is there any other way to speed this up? Before I had changed a line where I create the input
vector to int
from bool
and it resulted in a nice 2.3x speed increase. See here for benchmark.