Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Last active April 16, 2016 02:41
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/467dff5994d16fb4af23 to your computer and use it in GitHub Desktop.
Save BenGoldberg1/467dff5994d16fb4af23 to your computer and use it in GitHub Desktop.
Primes Iterator
use v6;
constant DEBUGGING = False;
my class P does Iterator {
has @!outbuf = (2, 3);
has @!primes;
has @!factors;
has $!a-prime = 3;
has $!a-squared-prime = $!a-prime ** 2;
has $!maybe-prime = 3;
method !mark-next-multiple( \factor ) {
my $where = factor;
$where += factor while @!factors[$where];
@!factors[ $where ] = factor;
}
method pull-one {
return @!outbuf.shift if @!outbuf;
repeat {
$!maybe-prime += 2;
if @!factors[0] {
say "$!maybe-prime is a multiple of @!factors[0]" if DEBUGGING;
self!mark-next-multiple: @!factors[0];
} elsif $!maybe-prime < $!a-squared-prime {
say "$!maybe-prime is prime" if DEBUGGING;
@!primes.push: $!maybe-prime;
@!outbuf.push: $!maybe-prime;
say "There are "~(+@!primes)~" enqueued primes" if DEBUGGING;
} elsif $!maybe-prime == $!a-squared-prime {
say "$!maybe-prime is a square" if DEBUGGING;
self!mark-next-multiple: $!a-prime;
say "There were "~(+@!primes)~" enqueued primes" if DEBUGGING;
$!a-prime = @!primes.shift;
$!a-squared-prime = $!a-prime * $!a-prime;
} else {
die "Critical math failure: Programmer or compiler is innumerate.";
}
so @!factors.shift;
} until @!outbuf.elems >= 16;
return @!outbuf.shift;
}
method is-lazy { True }
method count-only { Inf }
};
my $howlong = @*ARGS ?? @*ARGS.shift !! 3;
my $end = $howlong + now;
my $prior = 1;
my $cnt = 0;
for Seq.new(P.new) -> $p {
if ( False ) {
if ( grep *.is-prime, $prior ^..^ $p ) -> @uh-oh {
die "Skpped a prime, @uh-oh" if @uh-oh.elems == 1;
die "Skipped some primes, @uh-oh";
}
die "Not prime!" unless $p.is-prime;
}
$prior = $p;
++$cnt;
last if now >= $end;
}
say "In $howlong seconds, produced $cnt primes, from 2 to $prior";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment