Modular arithmetic: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|Raku}}: in-line code from module that cannot be installed (more instructive to boot))
m (syntax highlighting fixup automation)
Line 24:
=={{header|Ada}}==
Ada has modular types.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Modular_Demo is
Line 47:
Put (F_10); Put (" mod "); Put (Modul_13'Modulus'Image);
New_Line;
end Modular_Demo;</langsyntaxhighlight>
 
{{out}}
Line 54:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># allow for large integers in Algol 68G #
PR precision 200 PR
 
Line 75:
ESAC;
 
print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 83:
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
struct ModularArithmetic {
Line 134:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
Line 140:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace ModularArithmetic {
Line 225:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
Line 231:
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <ostream>
 
Line 305:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
version(unittest) {
Line 436:
assertEquals(b^^99, ModularInteger(12,13));
assertEquals(b^^100, ModularInteger(3,13));
}</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight lang="factor">USING: accessors generalizations io kernel math math.functions
parser prettyprint prettyprint.custom sequences ;
IN: rosetta-code.modular-arithmetic
Line 544:
} 2show ;
 
MAIN: modular-arithmetic-demo</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 678:
func main() {
fmt.Println(f(modRing(13), uint(10)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 685:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">-- We use a couple of GHC extensions to make the program cooler. They let us
-- 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)</langsyntaxhighlight>
 
{{out}}
Line 710:
J does not allow "operator redefinition", but J's operators are capable of operating consistently on values which represent modular integers:
 
<langsyntaxhighlight Jlang="j"> f=: (+./1 1,:_101{.1x)&p.</langsyntaxhighlight>
 
Task example:
 
<langsyntaxhighlight Jlang="j"> 13|f 10
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
{{works with|Java|8}}
<langsyntaxhighlight Javalang="java">public class ModularArithmetic {
private interface Ring<T> {
Ring<T> plus(Ring<T> rhs);
Line 804:
System.out.flush();
}
}</langsyntaxhighlight>
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
Line 829:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq">def assert($e; $msg): if $e then . else "assertion violation @ \($msg)" | error end;
 
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>
</lang>
'''Modular Arithmetic'''
<langsyntaxhighlight lang="jq"># "ModularArithmetic" objects are represented by JSON objects of the form: {value, mod}.
# The function modint::assert/0 checks the input is of this form with integer values.
 
Line 874:
 
# pretty print
def modint::pp: "«\(.value) % \(.mod)»";</langsyntaxhighlight>
''' Ring Functions'''
<langsyntaxhighlight lang="jq">def ring::add($A; $B):
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);</langsyntaxhighlight>
'''Evaluating ring::f'''
<langsyntaxhighlight lang="jq">def main:
(ring::f(1) | "f(\(1)) => \(.)"),
(modint::make(10;13)
| ring::f(.) as $out
| "f(\(ring::pp)) => \($out|ring::pp)");</langsyntaxhighlight>
{{out}}
Line 919:
 
Implements the <tt>Modulo</tt> struct and basic operations.
<langsyntaxhighlight lang="julia">struct Modulo{T<:Integer} <: Integer
val::T
mod::T
Line 946:
 
f(x) = x ^ 100 + x + 1
@show f(modulo(10, 13))</langsyntaxhighlight>
 
{{out}}
Line 952:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
interface Ring<T> {
Line 992:
val y = f(x)
println("x ^ 100 + x + 1 for x == ModInt(10, 13) is $y")
}</langsyntaxhighlight>
 
{{out}}
Line 1,000:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function make(value, modulo)
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)</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Mathematicalang="mathematica"><< FiniteFields`
x^100 + x + 1 /. x -> GF[13]@{10}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Nimlang="nim">import macros, sequtils, strformat, strutils
 
const Subscripts: array['0'..'9', string] = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]
Line 1,147:
 
var x = initModInt[13](10)
echo &"f({x}) = {x}^100 + {x} + 1 = {f(x)}."</langsyntaxhighlight>
 
{{out}}
Line 1,155:
 
This feature exists natively in GP:
<langsyntaxhighlight lang="parigp">Mod(3,7)+Mod(4,7)</langsyntaxhighlight>
 
=={{header|Perl}}==
There is a CPAN module called Math::ModInt which does the job.
<langsyntaxhighlight Perllang="perl">use Math::ModInt qw(mod);
sub f { my $x = shift; $x**100 + $x + 1 };
print f mod(10, 13);</langsyntaxhighlight>
{{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.
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
 
{{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 ).
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
 
congruence(Congruence, In, Fun, Out) :-
Line 1,245:
fun_2(L, [R]) :-
sum_list(L, R).
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight Pythonlang="python">import operator
import functools
 
Line 1,352:
 
print(f(Mod(10,13)))
# Output: Mod(1, 13)</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 1,364:
The third part fulfils the requirements of this task.
 
<langsyntaxhighlight Quackerylang="quackery ">[ stack ] is modulus ( --> s )
 
[ this ] is modular ( --> [ )
Line 1,409:
10 f echo cr
10 modularise f echo
modulus release cr</langsyntaxhighlight>
'''Output:'''
<pre>10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011
Line 1,418:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang 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</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,434:
 
Relevant portions of code in-lined from [https://raku.land/github:grondilu/Modular Modular].
<syntaxhighlight lang="raku" perl6line>class Modulo does Real {
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 );</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Redlang="red">Red ["Modular arithmetic"]
 
; 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]</langsyntaxhighlight>
{{out}}
<pre>f definition is: func [x][x ** 100 + x + 1]
Line 1,501:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby"># stripped version of Andrea Fazzi's submission to Ruby Quiz #179
 
class Modulo
Line 1,539:
 
p x**100 + x +1 ##<Modulo:0x00000000ad1998 @n=1, @m=13>
</syntaxhighlight>
</lang>
 
=={{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)].
<langsyntaxhighlight Scalalang="scala">object ModularArithmetic extends App {
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)
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class Modulo(n=0, m=13) {
 
method init {
Line 1,611:
 
func f(x) { x**100 + x + 1 }
say f(Modulo(10, 13))</langsyntaxhighlight>
{{out}}
<pre>1 「mod 13」</pre>
Line 1,619:
{{trans|Scala}}
 
<langsyntaxhighlight lang="swift">precedencegroup ExponentiationGroup {
higherThan: MultiplicationPrecedence
}
Line 1,678:
let y = f(x)
 
print("x ^ 100 + x + 1 for x = ModInt(10, 13) is \(y)")</langsyntaxhighlight>
 
{{out}}
Line 1,690:
as is shown here.
{{tcllib|pt::pgen}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require pt::pgen
 
Line 1,762:
list ${opns} variable [string range $sourcecode [expr {$from+1}] $to]
}
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="tcl"># The semantic evaluation engine; this is the part that knows mod arithmetic
oo::class create ModEval {
variable mod
Line 1,783:
 
# Put all the pieces together
set comp [CompileAST new [ModEval create mod13 13]]</langsyntaxhighlight>
Finally, demonstrating…
<langsyntaxhighlight lang="tcl">set compiled [$comp compile {$x**100 + $x + 1}]
set x 10
puts "[eval $compiled] = $compiled"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,794:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Option Base 1
Private Function mi_one(ByVal a As Variant) As Variant
If IsArray(a) Then
Line 1,875:
test 10
test [{10,13}]
End Sub</langsyntaxhighlight>{{out}}
<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#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Interface IAddition(Of T)
Line 1,969:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">// Semi-abstract though we can define a 'pow' method in terms of the other operations.
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))")</langsyntaxhighlight>
 
{{out}}
Line 2,036:
=={{header|zkl}}==
Doing just enough to perform the task:
<langsyntaxhighlight lang="zkl">class MC{
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)
}
}</langsyntaxhighlight>
Using GNU GMP lib to do the big math (to avoid writing a powmod function):
<langsyntaxhighlight lang="zkl">var BN=Import("zklBigNum");
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");</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits