Modular arithmetic: Difference between revisions
m
syntax highlighting fixup automation
SqrtNegInf (talk | contribs) (→{{header|Raku}}: in-line code from module that cannot be installed (more instructive to boot)) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 24:
=={{header|Ada}}==
Ada has modular types.
<
procedure Modular_Demo is
Line 47:
Put (F_10); Put (" mod "); Put (Modul_13'Modulus'Image);
New_Line;
end Modular_Demo;</
{{out}}
Line 54:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
PR precision 200 PR
Line 75:
ESAC;
print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) )</
{{out}}
<pre>
Line 83:
=={{header|C}}==
{{trans|C++}}
<
struct ModularArithmetic {
Line 134:
return 0;
}</
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
Line 140:
=={{header|C sharp|C#}}==
{{trans|Java}}
<
namespace ModularArithmetic {
Line 225:
}
}
}</
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
Line 231:
=={{header|C++}}==
{{trans|D}}
<
#include <ostream>
Line 305:
return 0;
}</
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
=={{header|D}}==
<
version(unittest) {
Line 436:
assertEquals(b^^99, ModularInteger(12,13));
assertEquals(b^^100, ModularInteger(3,13));
}</
{{out}}
<pre>
Line 457:
Also note that since <code>^</code> is not a generic word, we employ the strategy of renaming it to <code>**</code> inside our vocabulary and defining a new word named <code>^</code> that can also handle modular integers. This is an acceptable way to handle it because Factor has pretty good word-disambiguation faculties. I just wouldn't want to have to employ them for more frequently-used arithmetic.
<
parser prettyprint prettyprint.custom sequences ;
IN: rosetta-code.modular-arithmetic
Line 544:
} 2show ;
MAIN: modular-arithmetic-demo</
{{out}}
<pre>
Line 616:
=={{header|Go}}==
Go does not allow redefinition of operators. That element of the task cannot be done in Go. The element of defining f so that it can be used with any ring however can be done, just not with the syntactic sugar of operator redefinition.
<
import "fmt"
Line 678:
func main() {
fmt.Println(f(modRing(13), uint(10)))
}</
{{out}}
<pre>
Line 685:
=={{header|Haskell}}==
<
-- use / as an operator and 13 as a literal at the type level. (The library
-- also provides the fancy Zahlen (ℤ) symbol as a synonym for Integer.)
Line 698:
main :: IO ()
main = print (f 10)</
{{out}}
Line 710:
J does not allow "operator redefinition", but J's operators are capable of operating consistently on values which represent modular integers:
<
Task example:
<
1</
=={{header|Java}}==
{{trans|Kotlin}}
{{works with|Java|8}}
<
private interface Ring<T> {
Ring<T> plus(Ring<T> rhs);
Line 804:
System.out.flush();
}
}</
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
Line 829:
'''Preliminaries'''
<
def is_integer: type=="number" and floor == .;
Line 835:
# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
</syntaxhighlight>
'''Modular Arithmetic'''
<
# The function modint::assert/0 checks the input is of this form with integer values.
Line 874:
# pretty print
def modint::pp: "«\(.value) % \(.mod)»";</
''' Ring Functions'''
<
if $A|is_modint then modint::add($A; $B)
elif $A|is_integer then $A + $B
Line 901:
def ring::f($x):
ring::add( ring::add( ring::pow($x; 100); $x); 1);</
'''Evaluating ring::f'''
<
(ring::f(1) | "f(\(1)) => \(.)"),
(modint::make(10;13)
| ring::f(.) as $out
| "f(\(ring::pp)) => \($out|ring::pp)");</
{{out}}
Line 919:
Implements the <tt>Modulo</tt> struct and basic operations.
<
val::T
mod::T
Line 946:
f(x) = x ^ 100 + x + 1
@show f(modulo(10, 13))</
{{out}}
Line 952:
=={{header|Kotlin}}==
<
interface Ring<T> {
Line 992:
val y = f(x)
println("x ^ 100 + x + 1 for x == ModInt(10, 13) is $y")
}</
{{out}}
Line 1,000:
=={{header|Lua}}==
<
local v = value % modulo
local tbl = {value=v, modulo=modulo}
Line 1,060:
local x = make(10, 13)
local y = func(x)
print("x ^ 100 + x + 1 for "..x.." is "..y)</
{{out}}
<pre>x ^ 100 + x + 1 for ModInt(10, 13) is ModInt(1, 13)</pre>
Line 1,066:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The best way to do it is probably to use the finite fields package.
<
x^100 + x + 1 /. x -> GF[13]@{10}</
{{out}}
{1}<sub>13</sub>
Line 1,073:
=={{header|Nim}}==
Modular integers are represented as distinct integers with a modulus N managed by the compiler.
<
const Subscripts: array['0'..'9', string] = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]
Line 1,147:
var x = initModInt[13](10)
echo &"f({x}) = {x}^100 + {x} + 1 = {f(x)}."</
{{out}}
Line 1,155:
This feature exists natively in GP:
<
=={{header|Perl}}==
There is a CPAN module called Math::ModInt which does the job.
<
sub f { my $x = shift; $x**100 + $x + 1 };
print f mod(10, 13);</
{{out}}
<pre>mod(1, 13)</pre>
Line 1,168:
Phix does not allow operator overloading, but an f() which is agnostic about whether its parameter is a modular or normal int, we can do.
<!--<
<span style="color: #008080;">type</span> <span style="color: #000000;">mi</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">and</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
Line 1,223:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">({</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
Line 1,233:
=={{header|Prolog}}==
Works with SWI-Prolog versin 6.4.1 and module lambda (found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl ).
<
congruence(Congruence, In, Fun, Out) :-
Line 1,245:
fun_2(L, [R]) :-
sum_list(L, R).
</syntaxhighlight>
{{out}}
<pre> ?- congruence(13, [10], fun_1, R).
Line 1,264:
Thanks to duck typing, the function doesn't need to care about the actual type it's given. We also use the dynamic nature of Python to dynamically build the operator overload methods and avoid repeating very similar code.
<
import functools
Line 1,352:
print(f(Mod(10,13)))
# Output: Mod(1, 13)</
=={{header|Quackery}}==
Line 1,364:
The third part fulfils the requirements of this task.
<
[ this ] is modular ( --> [ )
Line 1,409:
10 f echo cr
10 modularise f echo
modulus release cr</
'''Output:'''
<pre>10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011
Line 1,418:
=={{header|Racket}}==
<
(require racket/require
;; grab all "mod*" names, but get them without the "mod", so
Line 1,428:
(define (f x) (+ (expt x 100) x 1))
(with-modulus 13 (f 10))
;; => 1</
=={{header|Raku}}==
Line 1,434:
Relevant portions of code in-lined from [https://raku.land/github:grondilu/Modular Modular].
<syntaxhighlight lang="raku"
has ($.residue, $.modulus);
multi method new($n, :$modulus) { self.new: :residue($n % $modulus), :$modulus }
Line 1,458:
sub f(\x) { x**100 + x + 1};
my $m-new = f( 10 Mod 13 );
say f( 10 Mod 13 );</
{{out}}
<pre>1 「mod 13」</pre>
Line 1,465:
This implementation of +,-,*,/ uses a loose test (object?) to check operands type.
As soon as one is a modular integer, the other one is treated as a modular integer too.
<
; defining the modular integer class, and a constructor
Line 1,494:
print ["f definition is:" mold :f]
print ["f((integer) 10) is:" f 10]
print ["f((modular) 10) is: (modular)" f m 10]</
{{out}}
<pre>f definition is: func [x][x ** 100 + x + 1]
Line 1,501:
=={{header|Ruby}}==
<
class Modulo
Line 1,539:
p x**100 + x +1 ##<Modulo:0x00000000ad1998 @n=1, @m=13>
</syntaxhighlight>
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/jOSxPQu/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/ZSeJw1lBRZiHenoQ6coDdA Scastie (remote JVM)].
<
private val x = new ModInt(10, 13)
private val y = f(x)
Line 1,591:
println("x ^ 100 + x + 1 for x = ModInt(10, 13) is " + y)
}</
=={{header|Sidef}}==
{{trans|Ruby}}
<
method init {
Line 1,611:
func f(x) { x**100 + x + 1 }
say f(Modulo(10, 13))</
{{out}}
<pre>1 「mod 13」</pre>
Line 1,619:
{{trans|Scala}}
<
higherThan: MultiplicationPrecedence
}
Line 1,678:
let y = f(x)
print("x ^ 100 + x + 1 for x = ModInt(10, 13) is \(y)")</
{{out}}
Line 1,690:
as is shown here.
{{tcllib|pt::pgen}}
<
package require pt::pgen
Line 1,762:
list ${opns} variable [string range $sourcecode [expr {$from+1}] $to]
}
}</
None of the code above knows about modular arithmetic at all, or indeed about actual expression evaluation.
Now we define the semantics that we want to actually use.
<
oo::class create ModEval {
variable mod
Line 1,783:
# Put all the pieces together
set comp [CompileAST new [ModEval create mod13 13]]</
Finally, demonstrating…
<
set x 10
puts "[eval $compiled] = $compiled"</
{{out}}
<pre>
Line 1,794:
=={{header|VBA}}==
{{trans|Phix}}<
Private Function mi_one(ByVal a As Variant) As Variant
If IsArray(a) Then
Line 1,875:
test 10
test [{10,13}]
End Sub</
<pre>x^100 + x + 1 for x == 10 is 1E+100
x^100 + x + 1 for x == modint(10,13) is modint(1,13)</pre>
Line 1,881:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Interface IAddition(Of T)
Line 1,969:
End Sub
End Module</
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
=={{header|Wren}}==
<
class Ring {
+(other) {}
Line 2,027:
var x = ModInt.new(10, 13)
System.print("x^100 + x + 1 for x = %(x) is %(f.call(x))")</
{{out}}
Line 2,036:
=={{header|zkl}}==
Doing just enough to perform the task:
<
fcn init(n,mod){ var N=n,M=mod; }
fcn toString { String(N.divr(M)[1],"M",M) }
Line 2,044:
self(z.divr(M)[1],M)
}
}</
Using GNU GMP lib to do the big math (to avoid writing a powmod function):
<
fcn f(n){ n.pow(100) + n + 1 }
f(1).println(" <-- 1^100 + 1 + 1");
n:=MC(BN(10),13);
(n+3).println(" <-- 10M13 + 3");
f(n).println(" <-- 10M13^100 + 10M13 + 1");</
{{out}}
<pre>
|