#include <bitset>
#include <iostream>
#include <vector>
template <std::size_t N>
struct prime_sieve
{
prime_sieve() : _sieve()
{
_sieve.flip();
for (std::size_t i = 0; i < N; ++i)
{
if (_sieve.test(i))
{
auto value = 3 + i * 2;
for (std::size_t j = i + value; j < N; j += value)
_sieve.reset(j);
}
}
}
std::vector<unsigned long long> get_primes() const
{
std::vector<unsigned long long> primes(1, 2);
for (std::size_t i = 0; i < N; ++i)
if (_sieve.test(i))
primes.push_back(3 + i * 2);
return primes;
}
private:
std::bitset<N> _sieve;
};
int main()
{
const std::size_t bits = 4000;
prime_sieve<bits> sieve;
auto primes = sieve.get_primes();
std::cout << "Found " << primes.size() << " primes using " << bits / 8 << " bytes.\n";
std::cout << "Last prime found: " << primes.back() << '\n';
}
I2luY2x1ZGUgPGJpdHNldD4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgoKdGVtcGxhdGUgPHN0ZDo6c2l6ZV90IE4+CnN0cnVjdCBwcmltZV9zaWV2ZQp7CiAgICBwcmltZV9zaWV2ZSgpIDogX3NpZXZlKCkKICAgIHsKICAgICAgICBfc2lldmUuZmxpcCgpOwogICAgICAgIAogICAgICAgIGZvciAoc3RkOjpzaXplX3QgaSA9IDA7IGkgPCBOOyArK2kpCiAgICAgICAgewogICAgICAgICAgICBpZiAoX3NpZXZlLnRlc3QoaSkpCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICAgIGF1dG8gdmFsdWUgPSAzICsgaSAqIDI7CiAgICAgICAgICAgICAgICBmb3IgKHN0ZDo6c2l6ZV90IGogPSBpICsgdmFsdWU7IGogPCBOOyBqICs9IHZhbHVlKQogICAgICAgICAgICAgICAgICAgIF9zaWV2ZS5yZXNldChqKTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KCiAgICBzdGQ6OnZlY3Rvcjx1bnNpZ25lZCBsb25nIGxvbmc+IGdldF9wcmltZXMoKSBjb25zdAogICAgewogICAgICAgIHN0ZDo6dmVjdG9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