Created
January 10, 2012 18:52
-
-
Save cslarsen/1590498 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes using bitsets on the heap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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). | |
* | |
* This sieve allocates the bitset on the heap, so you can calculate a lot | |
* of prime numbers. | |
*/ | |
#ifndef INC_PRIMES_H | |
#define INC_PRIMES_H | |
#include <bitset> | |
template<size_t PRIMES> | |
class prime_sieve | |
{ | |
public: | |
std::bitset<PRIMES> *p; | |
size_t primes; | |
prime_sieve() | |
{ | |
p = new std::bitset<PRIMES>(); | |
primes = 0; | |
rebuild(); | |
} | |
void rebuild() | |
{ | |
p->reset(); | |
p->flip(); | |
(*p)[0] = (*p)[1] = 0; | |
for ( size_t n=2; n < PRIMES; ++n ) | |
if ( (*p)[n] ) { | |
++primes; | |
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 primes; | |
} | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An updated version of this Sieve can be found in https://github.com/cslarsen/eulers-totient-function