in reply to Re: Quick search for modest numbers of prime numbers
in thread Quick search for modest numbers of prime numbers

I had a play years ago with primes and thought I had a pretty good algorithm until someone told me about Eratosthenes. Using his method was much faster. I have tried one variation since which was to use a vector to hold the primes rather than an array/list. The script will print primes as it goes until it reaches the threshhold of sqrt(limit) at which point it knows it has filled the vector up to the limit we have given. After that it prints the rest as fast as the frame buffer can handle.
#!/usr/local/bin/perl -w # $limit = shift or die "No limit supplied\n"; die "Limit is not integer\n" unless $limit =~ /^\d+$/; $sqrtLimit = sqrt $limit; $sieve = ""; vec($sieve, 0, 1) = 1; vec($sieve, 1, 1) = 1; vec($sieve, $limit, 1) = 0; $reached = 1; while($reached < $sqrtLimit) { $prime = $reached + 1; ++ $prime while vec($sieve, $prime, 1); print "$prime is a prime\n"; $fill = 2 * $prime; while($fill <= $limit) { vec($sieve, $fill, 1) = 1; $fill += $prime; } $reached = $prime; } foreach $value ($reached + 1 .. $limit) { print "$value is a prime\n" unless vec($sieve, $value, 1); }

On an ancient SPARCstation 20 with 150MHz processor it will calculate and print primes up to 100,000 in under 10 seconds.

Cheers

JohnGG