Re: The computational complexity of the Sieve of Eratosthenes
- From: Juha Nieminen <nospam@xxxxxxxxxxxxxx>
- Date: Wed, 30 Apr 2008 10:51:53 GMT
user923005 wrote:
Anyway, there are much better sieves now like the Sieve of Aitken.
Better in which sense? Maybe if you are calculating the first 10^20
primes then it's probably much faster.
It would be interesting, however, to see if the sieve of Atkin is
faster than the sieve of Eratosthenes for example in this case (C++):
namespace
{
const unsigned MAX_VALUE = 4200000000U;
std::bitset<MAX_VALUE/2> prime;
void init()
{
prime.set();
for(unsigned n = 3; n*n < MAX_VALUE; n += 2)
if(prime.test(n/2))
for(unsigned index = n*n; index < MAX_VALUE; index += n*2)
prime.reset(index/2);
}
bool isPrime(unsigned n)
{
if(n <= 1) return false;
return prime.test(n/2);
}
}
The init() function implements the sieve of Eratosthenes. In my
computer (3.4GHz Pentium4) using gcc 4.1.2 (using the compiler options
-O3 -march=pentium4), the init() function takes 1 minute and 12 seconds.
Certainly not the fastest possible way of initializing that bitset
properly, but I would be curious to see if the sieve of Atkin would
perform better.
Here's the rest of the program if you want to test:
namespace
{
unsigned getNthPrime(unsigned n)
{
if(n < 2) return 2;
unsigned count = 1, value = 1;
while(count < n)
{
value += 2;
if(prime.test(value/2))
++count;
}
return value;
}
}
#include <iostream>
int main()
{
init();
std::cout << "There are " << prime.count() << " primes smaller than "
<< MAX_VALUE
<< "\nThe 1000000th prime is " << getNthPrime(1000000)
<< std::endl;
}
.
- Follow-Ups:
- Re: The computational complexity of the Sieve of Eratosthenes
- From: user923005
- Re: The computational complexity of the Sieve of Eratosthenes
- References:
- The computational complexity of the Sieve of Eratosthenes
- From: Juha Nieminen
- Re: The computational complexity of the Sieve of Eratosthenes
- From: Richard Heathfield
- Re: The computational complexity of the Sieve of Eratosthenes
- From: Juha Nieminen
- Re: The computational complexity of the Sieve of Eratosthenes
- From: user923005
- The computational complexity of the Sieve of Eratosthenes
- Prev by Date: Re: Programming to Beat the Odds in Gaming
- Next by Date: Re: Moving cd-rom head manually
- Previous by thread: Re: The computational complexity of the Sieve of Eratosthenes
- Next by thread: Re: The computational complexity of the Sieve of Eratosthenes
- Index(es):
Relevant Pages
|