Skip to content

Instantly share code, notes, and snippets.

@dogbert17
Created May 9, 2021 15:35
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 dogbert17/0c20f82c0229b12503001cefcff83df9 to your computer and use it in GitHub Desktop.
Save dogbert17/0c20f82c0229b12503001cefcff83df9 to your computer and use it in GitHub Desktop.
Slowdown example
# How many circular primes are there below one million?
# real 0m46.458s
# user 0m46.080s
# sys 0m0.068s
# This is Rakudo version 2016.03-110-g5bfc8fb built on MoarVM version 2016.03-104-g10d3971
use v6;
my $max = 1_000_000;
# find all primes up to $max using The Sieve of Erathostenes
my int @a = (0..$max);
for (2..($max div 2)) -> $i {
my $j = 2;
@a[$i * $j++] = 1 while $i * $j <= $max;
}
# remove discarded numbers and store the rest in a set for ease of lookup
my @primes = @a.grep(-> $num {$num > 1});
my $set = SetHash.new(@primes);
say "The number of circular primes is ", @primes.grep( -> $prime { &checkPrime($prime) } ).elems;
sub checkPrime($p) {
my $tmp = $p;
my $numDigits = (~$p).chars;
return True if $numDigits == 1;
loop (my $i = 1; $i <= $numDigits - 1; $i++) {
$tmp = $tmp % 10 * 10 ** ($numDigits - 1) + $tmp div 10;
return False if !$set{$tmp};
}
return True;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment