Last active
August 29, 2015 14:18
-
-
Save BenGoldberg1/c9f2a3f642c30fc343fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v6; | |
sub primes-list(Bool $use-wheel) { | |
my @start = $use-wheel ?? (2, 3) !! (2); | |
my @sieve; | |
my $i = @start-1; | |
my $p = @start[$i]; | |
my $q = $p*$p; | |
my $n = $p; | |
my \incr = $use-wheel ?? 2 !! 1; | |
@start, -> *@primes { | |
loop { | |
$n += incr; | |
if ( @sieve.shift ) -> @s { | |
# $n is not prime. It's unique prime factors (-1) are @s. | |
@sieve[ $_ ].push: $_ for @s; | |
} elsif ( $n < $q ) { | |
# $n is prime. | |
last; | |
} else { | |
# $n is equal to $q, which in turn is equal to $p*$p, | |
# which of course is composite. Store the next composite | |
# after $n into the sieve. | |
my \p1 = $p - 1; | |
@sieve[ p1 ].push: p1; | |
$p = @primes[ ++$i ]; | |
#print "prime number $i is ",$p; | |
$q = $p*$p; | |
} | |
} | |
$n; | |
} ... *; | |
} | |
#"$_, ".print for primes-list(True); | |
for (False, True) -> $use-wheel { | |
say "use-wheel: $use-wheel"; | |
my $n = 200; | |
my $count = 0; | |
my $elapsed; | |
my $start = now; | |
loop { | |
my $p = primes-list($use-wheel)[$n-1]; | |
$p.say unless $count; | |
++$count; | |
$elapsed = now - $start; | |
last if $elapsed >= 5 and $count >= 5; | |
} | |
say "In $elapsed seconds, we did $count iterations."; | |
if ( $elapsed > $count ) { | |
say "This is ", $elapsed/$count, " seconds per iteration"; | |
} else { | |
say "This is ", $count/$elapsed, " iteration per second"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment