Modular arithmetic: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
(→‎{{header|Raku}}: update code to recent module version)
Line 1,433: Line 1,433:
(formerly Perl 6)
(formerly Perl 6)


Relevant portions of code in-lined from [https://raku.land/github:grondilu/Modular Modular].
We'll use the [https://raku.land/github:grondilu/finite-fields-raku FiniteFields] repo.
<syntaxhighlight lang="raku" line>class Modulo does Real {
has ($.residue, $.modulus);
multi method new($n, :$modulus) { self.new: :residue($n % $modulus), :$modulus }
method Bridge { $.residue }
multi method gist { "$.residue 「mod $.modulus」" }
}


<syntaxhighlight lang="raku" line>use FiniteField;
sub infix:<Mod>(Int $n, Int $modulus where * > 1) returns Modulo {
$*modulus = 13;
Modulo.new: $n, :$modulus
}


sub f(\x) { x**100 + x + 1};
multi infix:<+>(Modulo $a, Int $b) { $a + ($b Mod $a.modulus) }
multi infix:<+>(Int $a, Modulo $b) { ($a Mod $b.modulus) + $b }


say f(10);</syntaxhighlight>
multi infix:<+>(Modulo $a, Modulo $b where $a.modulus ~~ $b.modulus) returns Modulo {
Modulo.new: $a.Bridge + $b.Bridge, :modulus($b.modulus)
}

multi infix:<**>(Modulo $a, Int $e) returns Modulo {
Modulo.new: $a.Bridge.expmod($e, $a.modulus), :modulus($a.modulus)
}

sub f(\x) { x**100 + x + 1};
my $m-new = f( 10 Mod 13 );
say f( 10 Mod 13 );</syntaxhighlight>
{{out}}
{{out}}
<pre>1 「mod 13」</pre>
<pre>1</pre>


=={{header|Red}}==
=={{header|Red}}==