I am implementing the Sieve of Eratosthenes. I am stuck on the first step: deciding which data structure to use. Put simply, the Sieve of Eratosthenes starts with a list of consecutive numbers (e.g. 2,3,4,5,...99, 100). Then, certain numbers are crossed out and never considered again. What's the best data structure to use? The limit (100 in the example) is not known until run time, though 2 is always the starting number.
I have seen a few different solutions. The limit n is of type mpz_class
bool primes[n]bool* primesstd::vector<bool> primesstd::bitset<n> primesvectorwith the parameterintorunsigned charbecause they would would be more efficient thanbool- for vector and array based solutions, allocate
n+1elements (as seen here) I guess this is so the value ofnwould be at the last element and fewer subtractions are needed inside a loop.
Some of this information comes from this Code Review question. @Jamal states "there are actually issues with std::vector specifically" but doesn't elaborate. Also I red somewhere that the size of unsigned char is guaranteed to be equal or smaller than bool making it the better choice.