Skip to content

Instantly share code, notes, and snippets.

@moritz
Created January 17, 2012 12:39
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 moritz/75b078d082ce95d5972a to your computer and use it in GitHub Desktop.
Save moritz/75b078d082ce95d5972a to your computer and use it in GitHub Desktop.
optimized rabin-miller prime test (Rakudo)
my Bool multi sub is_prime(PrimeCandidate $n, Int $k) {
my Int $d = $n - 1;
my Int $s = 0;
while $d %% 2 {
$d div= 2;
$s++;
}
for (2 ..^ $n).pick($k) -> $a {
my $x = nqp::expmod_I(nqp::p6decont($a), nqp::p6decont($d), nqp::p6decont($n), Int);
# my $x = modexp($a, $d, $n);
next if $x == 1 or $x == $n - 1;
my int $max = nqp::unbox_i($s);
loop ( my int $i = 0; $i < $max; $i = $i + 1) {
$x = nqp::expmod_I(nqp::p6decont($x), 2, nqp::p6decont($n), Int);
return False if $x == 1;
last if $x == $n - 1;
}
return False if $x !== $n - 1;
}
return True;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment