Modular arithmetic: Difference between revisions
→{{header|Raku}}: in-line code from module that cannot be installed (more instructive to boot)
m (→{{header|J}}) |
SqrtNegInf (talk | contribs) (→{{header|Raku}}: in-line code from module that cannot be installed (more instructive to boot)) |
||
Line 1,432:
=={{header|Raku}}==
(formerly Perl 6)
Relevant portions of code in-lined from [https://raku.land/github:grondilu/Modular Modular].
<lang perl6>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」" }
}
sub infix:<Mod>(Int $n, Int $modulus where * > 1) returns Modulo {
Modulo.new: $n, :$modulus
}
multi infix:<+>(Modulo $a, Int $b) { $a + ($b Mod $a.modulus) }
multi infix:<+>(Int $a, Modulo $b) { ($a Mod $b.modulus) + $b }
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};
say f( 10 Mod 13 );</lang>
{{out}}
<pre>1 「mod 13」</pre>
=={{header|Red}}==
This implementation of +,-,*,/ uses a loose test (object?) to check operands type.
|