Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Last active August 14, 2016 20:32
Show Gist options
  • Save BenGoldberg1/56d3ed91959c34430dd9c763b653162f to your computer and use it in GitHub Desktop.
Save BenGoldberg1/56d3ed91959c34430dd9c763b653162f to your computer and use it in GitHub Desktop.
# This code is based on the python code at:
# http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Fast_infinite_generator_using_a_wheel
sub primes { gather {
.take for 2, 3, 5, 7;
my @gaps := [
2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,
6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ];
my sub wheel_prime_pairs() { gather {
take (11, 0);
my $bps = wheel_prime_pairs().iterator;
my ($p, $pi) = $bps.pull-one;
my $q = $p * $p;
my %sieve;
my ($n, $ni) = (13, 1);
loop {
if ( not %sieve{$n} :exists ) {
if $n < $q {
take ($n, $ni);
} else {
my $npi = $pi + 1;
$npi = 0 if $npi > 47;
%sieve{$q + $p * @gaps[$pi]} = ($p, $npi);
($p, $pi) = $bps.pull-one;
$q = $p * $p;
}
} else {
my ($s, $si) = %sieve{$n} :delete;
my $nxt = $n + $s * @gaps[$si++];
$si = 0 if $si > 47;
while %sieve{$nxt} :exists {
$nxt += @gaps[$si++];
$si = 0 if $si > 47;
}
%sieve{$nxt} = ($s, $si);
}
$n += @gaps[$ni++];
$ni = 0 if $ni > 47;
}
} };
for wheel_prime_pairs() -> ($p, $pi) {
$p.take;
}
} };
my $prior = 2;
for primes() -> $p {
die "$p isn't prime!" unless $p.is-prime;
my @skipped = grep *.is-prime, $prior^..^$p;
die "These primes were wrongly ommited: @skipped." if @skipped;
$prior = $p;
last if now > INIT { 3 + now }
}
print $prior;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment