Jump to content

Tonelli-Shanks algorithm: Difference between revisions

m
→‎{{header|Perl 6}}: Minor code simplifications, add missing failing test
m (→‎{{header|Sidef}}: code simplifications)
m (→‎{{header|Perl 6}}: Minor code simplifications, add missing failing test)
Line 410:
 
<lang perl6># Legendre operator (𝑛│𝑝)
sub infix:<│> (Int \𝑛, Int \𝑝 where (𝑝.is-prime and&& ?(𝑝 != 2))) {
given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) {
when 0 { 0 }
Line 418:
}
 
sub tonelli-shanks ( \𝑛, \𝑝 where ((𝑛│𝑝) > 0 )) {
my $𝑄 = 𝑝 - 1;
my $𝑆 = 0;
$𝑄 +>= 1 and $𝑆++ while $𝑄 %% 2;
return 𝑛.expmod((𝑝+1) div 4, 𝑝) if $𝑆 == 1;
my $𝑐 = ((2..𝑝).first: (*│𝑝) < 0).expmod($𝑄, 𝑝);
my $𝑐;
for 2 .. 𝑝 {
$𝑐 = .expmod($𝑄, 𝑝) and last if ($_│𝑝) < 0;
}
my $𝑅 = 𝑛.expmod( ($𝑄+1) +> 1, 𝑝 );
my $𝑡 = 𝑛.expmod( $𝑄, 𝑝 );
mywhile ($𝑀𝑡-1) =% $𝑆;𝑝 {
my $b;
while (($𝑡-1) % 𝑝) {
my $𝑡2 = $𝑡² % 𝑝;
for 1 .. $𝑀𝑆 {
if ($𝑡2-1) %% 𝑝 {
$b = $𝑐.expmod( 1 +< ( $𝑀 𝑆- 1 - $_ ), 𝑝 );
$𝑀𝑆 = $_;
last;
}
Line 452 ⟶ 448:
(56, 101),
(1030, 10009),
(1032, 10009),
(44402, 100049),
(665820697, 1000000009),
Line 460 ⟶ 457:
 
for @tests -> ($n, $p) {
try my $t = tonelli-shanks($n, $p);
diesay "No solution for ({$n}, {$p})." and next if !$t or ($t² - $n) % $p;
say "Roots of $n are ($t, {$p-$t}) mod $p";
}</lang>
Line 468 ⟶ 465:
Roots of 56 are (37, 64) mod 101
Roots of 1030 are (1632, 8377) mod 10009
No solution for (1032, 10009).
Roots of 44402 are (30468, 69581) mod 100049
Roots of 665820697 are (378633312, 621366697) mod 1000000009
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.