-
-
Save moritz/75b078d082ce95d5972a to your computer and use it in GitHub Desktop.
optimized rabin-miller prime test (Rakudo)
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
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