Cipolla's algorithm: Difference between revisions

m
→‎{{header|Perl 6}}: Minor code simplifications.
m (→‎{{header|Perl 6}}: Minor code simplifications.)
Line 359:
 
<lang perl6># Legendre operator (𝑛│𝑝)
sub infix:<│> (Int \𝑛, Int \𝑝 where (𝑝.is-prime and&& ?(𝑝 != 2))) {
given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) {
when 0 { 0 }
Line 376:
note "Invalid parameters ({𝑛}, {𝑝})"
and return Nil if (𝑛│𝑝) != 1;
my ($ω2, $a);
formy 0$a ..= * {0;
loop $a = $_;{
last if ($ω2 = ($a² - 𝑛) % 𝑝)│𝑝 < 0;
last if ($ω2│𝑝) < 0a++;
}
 
# define a local multiply operator for Field coordinates
multi sub infix:<*> ( Fp $a, Fp $b ){
Fp.new: :x(($a.x * $b.x + $a.y * $b.y * $ω2) % 𝑝),
:xy(($a.x * $b.xy + $ab.yx * $ba.y) * $ω2) % 𝑝),
:y(($a.x * $b.y + $b.x * $a.y) % 𝑝)
)
}
 
my $r = Fp.new(: :x(1), :y(0) );
my $s = Fp.new(: :x($a), :y(1) );
 
for (𝑝+1) +> 1, * +> 1 ...^ 01 {
$r *= $s if $_ % 2;
$s *= $s;
Line 416 ⟶ 414:
for @tests -> ($n, $p) {
my $r = cipolla($n, $p);
say $r ?? "Roots of $n are ($r, {$p-$r}) mod $p"
if $r {
say !! "RootsNo ofsolution $n arefor ($rn, {$p-$r}) mod $p"
}
} else {
}</lang>
say "No solution for ($n, $p)"
}
}</lang>
{{out}}
<pre>Roots of 10 are (6, 7) mod 13
10,327

edits