Skip to content

Instantly share code, notes, and snippets.

@hindol
Created October 12, 2012 03:49
Show Gist options
  • Save hindol/3877195 to your computer and use it in GitHub Desktop.
Save hindol/3877195 to your computer and use it in GitHub Desktop.
Prime generator using Sieve of Eratothenes, uses a BitSet to save space
void AllPrimesTill(int32_t till, std::vector<int32_t>& primes)
{
BitSet<true> isPrime(till + 1);
isPrime.Reset(0);
isPrime.Reset(1);
int32_t cap = static_cast<int32_t>( std::sqrt(till) ) + 1;
primes.clear();
for (int32_t i = 2; i <= cap; ++i)
{
if (isPrime[i])
{
for (int32_t i2 = i * i; i2 <= till; i2 += i)
{
isPrime.Reset(i2);
}
}
}
for (std::size_t i = 0; i < isPrime.Size(); ++i)
{
if (isPrime[i])
primes.push_back(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment