Modular arithmetic: Difference between revisions
Content added Content deleted
(→{{header|Nim}}: insert Mathematica solution) |
|||
Line 740: | Line 740: | ||
{{out}} |
{{out}} |
||
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre> |
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre> |
||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
'''Adapted from [[#C|C]]''' |
|||
The following presentation uses jq's support for modules and includes some error-checking. |
|||
If all the functions are placed in a file, say "modint.jq", we can |
|||
then execute the function named "main" by first importing the |
|||
module, and then prefixing the function name with the name of the |
|||
module: |
|||
<lang jq>import "modint" as modint {search: "."}; |
|||
modint::main</lang> |
|||
'''module "modint"''' |
|||
<lang jq> |
|||
module {name: "modint"}; |
|||
# In this module, "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. |
|||
# Preliminaries |
|||
def assert($e; $msg): if $e then . else "assertion violation @ \($msg)" | error end; |
|||
def is_integer: type=="number" and floor == .; |
|||
def assert: |
|||
assert(type=="object"; "object expected") |
|||
| assert(has("value"); "object should have a value") |
|||
| assert(has("mod"); "object should have a mod") |
|||
| assert(.value | is_integer; "value should be an integer") |
|||
| assert(.mod | is_integer; "mod should be an integer"); |
|||
# modint |
|||
def make($value; $mod): |
|||
assert($value|is_integer; "value should be an integer") |
|||
| assert($mod|is_integer; "mod should be an integer") |
|||
| { value: ($value % $mod), mod: $mod}; |
|||
def add($modintA; $B): |
|||
if ($B|type) == "object" |
|||
then assert($modintA.mod == $B.mod ; "add") |
|||
| make( $modintA.value + $B.value; $modintA.mod ) |
|||
else make( $modintA.value + $B; $modintA.mod ) |
|||
end; |
|||
def mul($modintA; $B): |
|||
if ($B|type) == "object" |
|||
then assert($modintA.mod == $B.mod ; "mul") |
|||
| make( $modintA.value * $B.value; $modintA.mod ) |
|||
else make( $modintA.value * $B; $modintA.mod ) |
|||
end; |
|||
def pow($modintA; $pow): |
|||
assert($pow | is_integer; "pow") |
|||
| reduce range(0; $pow) as $i ( make(1; $modintA.mod); |
|||
mul( .; $modintA) ); |
|||
# pretty print |
|||
def pp: "«\(.value) % \(.mod)»"; |
|||
def f($x): |
|||
add( add( pow($x; 100); $x); 1); |
|||
def main: |
|||
make(10;13) |
|||
| f(.) as $out |
|||
| "f(\(pp)) => \($out|pp)";</lang> |
|||
{{out}} |
|||
<pre> |
|||
f(«10 % 13») => «1 % 13» |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |