...with the actual calculation taking one single grep statement:
That's rather misleading. There's a nested map as well, but you didn't count that.
I've played with this idea quite a bit in the past, and never cared much for over-complexifying it. I'll post 2 ideas here, one from Abigail from CLPM, and one I dreamed up for my keystroke programmable TI-95 longer ago than I care to imagine.
From Usenet, June '97:
#!/usr/local/bin/perl -wl
use strict;
my ($prime, $max) = (2, shift || 50); # First prime, max numb
+er.
my @sieve = (0, 0, map {1;} ($prime .. $max)); # Init sieve.
while ((my $product = $prime * $prime) <= $max) {
do {$sieve [$product] = 0;}
while (($product += $prime) <= $max);
do {$prime ++;}
while !$sieve [$prime];
}
map {print if $sieve [$_];} (0 .. $max);
I like this because it's easy to understand, and reasonably efficient. For instance, once the next $prime is found, all unmarked candidates less than the $prime**2 are also prime -- no need for trial division on them.
Notice that this takes up some memory. On the TI-95, there was only a little memory, so computing the first million primes would be painful. And keeping a list of anything besides primes was even more limiting. With that in mind, here's another way:
#!/your/perl/here
use strict;
use warnings;
use integer;
$|=1;
my $stop = (shift or 50);
print "2";
my @primes;
TRIAL_PRIME:
for (my $i=3;$i<$stop;$i+=2)
{
for my $p (@primes)
{
next TRIAL_PRIME unless ( $i % $p );
}
push @primes, $i;
print ", $i";
}
print "\n";
exit;
That's reasonably fast with a small memory footprint. For a slight speedup, and less memory, use a bit vector.
Update: Can't spell Abigail (at least the link was correct?)
-QM
--
Quantum Mechanics: The dreams stuff is made of
|