, .
:
- .is-prime ( @DanaJ, , ).
- Perl 6 , , (.. Perl6ish).
- ( Perl 5) .
- . 😋
: Cimes Tilmes 'Primesieve. , ! (.. )!
, , Primesieve / (?), , /.
: " " Timbus. , ...
: Perl6 . ( ) 1..99 . (, √ ( )), Perl 6. : ; , .
: Math:: Primesieve , script.
use v6.c;
sub primes-is-prime
{
(^∞).grep: *.is-prime;
}
sub primes-sieve(Int $max)
{
my @sieve;
lazy gather for 2..$max -> $p {
next if @sieve[$p];
take $p;
for 2*$p, 3*$p ... $max -> $n {
@sieve[$n] = True;
}
}
}
sub primes-sieve2(Int $max)
{
my int @sieve;
lazy gather {
take 2;
loop (my int $p = 3; $p ≤ $max; $p += 2) {
next if @sieve[$p];
take $p;
loop (my int $n = 3*$p; $n ≤ $max; $n += 2*$p) {
@sieve[$n] = 1;
}
}
}
}
sub primes-sieve3(Int $max)
{
my int @sieve;
my $max2 = ($max-1) div 2;
lazy gather {
take 2;
for 1 .. $max2 -> int $i {
next if @sieve[$i];
take 2*$i + 1;
my $max3 = ($max2 - $i) div (2*$i + 1);
for 1 .. $max3 -> int $j {
@sieve[(2*$j + 1)*$i + $j] = 1;
}
}
}
}
sub primes-sieve4
{
my $max = 100;
my int @sieve = 1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,
1,0,1,1,0,0,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1;
lazy gather {
take 2;
my int $min-i = 1;
loop {
my int $max-i = ($max-1) div 2;
for $min-i .. $max-i -> int $i {
take 2*$i + 1 unless @sieve[$i];
}
for 1 .. ((2*$max).sqrt.floor-1) div 2 -> int $i {
next if @sieve[$i];
my int $p = 2*$i + 1;
my int $min-j = max(($max-i - $i) div $p, $i);
my int $max-j = (2*$max-i + 1 - $i) div $p;
for $min-j .. $max-j -> int $j {
@sieve[$i + $p*$j] = 1;
}
}
$max *= 2;
$min-i = $max-i+1;
}
}
}
sub primes-perl5
{
use Math::Prime::Util:from<Perl5> <prime_iterator>;
my $it = prime_iterator;
lazy gather {
loop {
take $it.();
}
}
}
sub primes-primesieve($max)
{
use Math::Primesieve;
return Math::Primesieve.new.primes($max);
}
sub primes-primesieve-iterator
{
use Math::Primesieve;
my $iterator = Math::Primesieve::iterator.new;
lazy gather {
loop {
take $iterator.next;
}
}
}
sub primes-cheat
{
lazy $*PROGRAM.sibling('primes1.txt').words.map(+*);
}
sub timer(&code)
{
my $start = now;
&code();
my $elapsed = now - $start;
say "Elapsed: $elapsed.fmt('%.3f')s";
}
sub MAIN
{
my $nth = 50_000;
my $max = 612_000;
timer {
my @primes = primes-is-prime;
say "Using .is-prime: @primes[$nth]";
}
timer {
my @primes = primes-sieve($max);
say "Using a sieve (simple Perl 6 style): @primes[$nth]";
}
timer {
my @primes = primes-sieve2($max);
say "Using a sieve (optimized): @primes[$nth]";
}
timer {
my @primes = primes-sieve3($max);
say "Using a sieve (even more optimized): @primes[$nth]";
}
timer {
my @primes = primes-sieve4;
say "Using a flexible sieve size (further optimized): @primes[$nth]";
}
timer {
my @primes = primes-perl5;
say "Using a Perl 5 module: @primes[$nth]";
}
timer {
my @primes = primes-primesieve($max);
say "Using Primesieve module: @primes[$nth]";
}
timer {
my @primes = primes-primesieve-iterator;
say "Using Primesieve module (iterator): @primes[$nth]";
}
timer {
my @primes = primes-cheat;
say "Cheating: @primes[$nth]";
}
}