Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created October 25, 2011 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cslarsen/1314317 to your computer and use it in GitHub Desktop.
Save cslarsen/1314317 to your computer and use it in GitHub Desktop.
A simple sieve of Eratosthenes using bitsets and vectors
/*
* A simple sieve of Eratosthenes using bitsets, written by Christian Stigen Larsen
* You are free to use this code for anything (i.e., public domain).
*/
#ifndef INC_PRIMES_H
#define INC_PRIMES_H
#include <vector>
#include <algorithm>
#include <bitset>
template<size_t PRIMES>
class prime_sieve
{
public:
std::bitset<PRIMES> p;
std::vector<int64_t> v;
prime_sieve()
{
rebuild();
}
void rebuild()
{
p.reset();
p.flip();
p[0] = p[1] = 1;
for ( size_t n=2; n < PRIMES; ++n )
if ( p[n] ) {
v.push_back(n);
for ( size_t m=n<<1; m < PRIMES; m += n )
p[m] = 0;
}
}
inline bool isprime(int64_t n) const
{
return p[n];
}
inline size_t size() const
{
return v.size();
}
inline std::vector<int64_t>::const_iterator first() const
{
return v.begin();
}
inline std::vector<int64_t>::const_iterator last() const
{
return v.end();
}
inline std::vector<int64_t>::const_iterator find(int64_t n) const
{
return std::equal_range(v.begin(), v.end(), n).second;
}
};
#endif
@cslarsen
Copy link
Author

cslarsen commented Nov 8, 2012

An updated version of this sieve can be found at https://github.com/cslarsen/eulers-totient-function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment