Created
May 9, 2021 15:35
-
-
Save dogbert17/0c20f82c0229b12503001cefcff83df9 to your computer and use it in GitHub Desktop.
Slowdown example
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
# 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