Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Created November 22, 2015 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenGoldberg1/7e365fc0a9fe49eed7be to your computer and use it in GitHub Desktop.
Save BenGoldberg1/7e365fc0a9fe49eed7be to your computer and use it in GitHub Desktop.
Primes Iterator with Splices
use v6;
constant DEBUGGING = False;
my class PrimesI does Iterator {
has @!primes = (2, 3);
has @!sieve = (Any xx 3);
has $!p = 3;
has $!q = $!p * $!p;
has $!n = $!p;
method pull-one returns Int {
return @!primes.shift if @!primes and @!primes[0] < 4;
my $p_ix = 0;
for @!sieve.kv -> $offset, $s {
$!n += 2;
print "n, p and q are $!n, $!p, $!q, sieve is " ~ @!sieve.gist ~ " " if DEBUGGING;
if $s {
say "Composite" if DEBUGGING;
# n is not prime. It's prime factors, uniqified, are @s.
@!sieve[ $offset+$_ ].push: $_ for @$s;
} elsif ( $!n < $!q ) {
say "Prime; sieve is now ", @!sieve if DEBUGGING;
# n is prime.
@!sieve.splice: 0, $offset+1;
@!primes.splice: 0, $p_ix;
@!primes.push: $!n;
return $!n;
} else {
# n is equal to q, which in turn is equal to p*p,
# which of course is composite.
say "Square; primes is " ~ @!primes if DEBUGGING;
# Store the next composite after n in the sieve.
@!sieve[ $offset+$!p ].push: $!p;
$!p = @!primes[ $p_ix++ ];
$!q = $!p*$!p;
}
};
die "Shouldn't get here!";
};
method is-lazy { True }
method count-only { Inf }
};
my $howlong = @*ARGS ?? @*ARGS.shift !! 2;
my $stop = time + $howlong;
my $count = 0;
my @p;
say "Start";
for Seq.new(PrimesI.new) {
last if time > $stop;
push @p, $_;
};
say "Produced {+@p} primes: {@p}";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment