My code is as follows:
int main(){
vector<int> primes;
vector<int> primesSum;
int tally = 1;
bool primeFound = false;
while (true) {
int i = 0;
while (!primeFound) {
primeFound = true;
tally++;
for (i = 0; i < (int)primes.size(); i++) {
if (tally == primesSum[i]) {
primeFound = false;
primesSum[i] += primes[i];
}
}
}
primeFound = false;
primesSum.push_back(tally*2);
primes.push_back(tally);
}
}
It seems to generate prime numbers fine but I was wondering if I could increase its efficiency by implementing the rule that all primes are 6n +/- 1 after 2 and 3. That would seem to sacrifice my achievement of initially empty vectors though.
I've seen prime number verifiers that make use of the 6n +/- i rule but not really in sieve programs, likely as it breaks the 2 filter.
Edit: as an aside I would prefer to not use modulo as that is another achievement for this program, unless a modulo is more efficient (time-wise not space-wise) than what I currently have.
Here is some code that I wrote to efficiently generate primes using a sieve that only considers integers that are +-1 mod 6. It is written as a generator using a coroutine library, but the logic is equivalent. It uses a
vectorofuint64_t's as a bit mask.There are no modulo's related to computing the primes, but they are used to access the bitmap.
Update
I extracted my original code from the generator and created a simple function that puts the primes in a vector. One method uses the +-1 mod 2 search and the other +-1 mod 6 search. I also extracted the OP's code into a function.
I ran some simple timing measurements on an M1 Max (arm64).
The code and build instructions can be found at the GitHub repo cpp-core/so
Code
End Update
You can easily adapt it to construct a
vectorof primes by replacing eachco_yieldwithvec.push_back.