Jump to content

Modular inverse: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 22:
{{trans|C}}
 
<langsyntaxhighlight lang="11l">F mul_inv(=a, =b)
V b0 = b
V x0 = 0
Line 36:
R x1
 
print(mul_inv(42, 2017))</langsyntaxhighlight>
 
{{out}}
Line 44:
 
=={{header|8th}}==
<syntaxhighlight lang="forth">
<lang Forth>
\ return "extended gcd" of a and b; The result satisfies the equation:
\ a*x + b*y = gcd(a,b)
Line 69:
 
42 2017 n:invmod . cr bye
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 76:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">INT FUNC ModInverse(INT a,b)
INT t,nt,r,nr,q,tmp
 
Line 114:
Test(-486,217)
Test(40,2018)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Modular_inverse.png Screenshot from Atari 8-bit computer]
Line 127:
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO;use Ada.Text_IO;
procedure modular_inverse is
Line 147:
exception when others => Put_Line ("The inverse doesn't exist.");
end modular_inverse;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">
BEGIN
PROC modular inverse = (INT a, m) INT :
Line 186:
CO
END
</syntaxhighlight>
</lang>
{{out}}
<pre>42 ^ -1 (mod 2017) = 1969
Line 195:
{{trans|D}}
 
<langsyntaxhighlight lang="rebol">modInverse: function [a,b][
if b = 1 -> return 1
 
Line 211:
]
 
print modInverse 42 2017</langsyntaxhighlight>
 
{{out}}
Line 219:
=={{header|AutoHotkey}}==
Translation of [http://rosettacode.org/wiki/Modular_inverse#C C].
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, % ModInv(42, 2017)
 
ModInv(a, b) {
Line 237:
x1 += b0
return x1
}</langsyntaxhighlight>
{{out}}
<pre>1969</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MODULAR_INVERSE.AWK
# converted from C
Line 270:
return(x1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 279:
==={{header|ASIC}}===
{{trans|Pascal}}
<langsyntaxhighlight lang="basic">
REM Modular inverse
E = 42
Line 309:
ModInv = D
RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 319:
{{works with|Commodore BASIC|3.5}}
{{works with|Nascom ROM BASIC|4.7}}
<langsyntaxhighlight lang="gwbasic">
10 REM Modular inverse
20 LET E = 42
Line 339:
600 LET M = D
610 RETURN
</syntaxhighlight>
</lang>
 
=={{header|Batch File}}==
Line 345:
 
{{trans|Perl}}
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
%== Calls the "function" ==%
Line 387:
if !t! lss 0 set /a t+=b
set %3=!t!
goto :EOF</langsyntaxhighlight>
{{Out}}
<pre>1969
Line 396:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let mulinv(a, b) =
Line 426:
show(-486, 217)
show(40, 2018)
$)</langsyntaxhighlight>
{{out}}
<pre>42, 2017 -> 1969
Line 436:
=={{header|Bracmat}}==
{{trans|Julia}}
<langsyntaxhighlight lang="bracmat">( ( mod-inv
= a b b0 x0 x1 q
. !arg:(?a.?b)
Line 451:
)
& out$(mod-inv$(42.2017))
};</langsyntaxhighlight>
Output
<pre>1969</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int mul_inv(int a, int b)
Line 475:
printf("%d\n", mul_inv(42, 2017));
return 0;
}</langsyntaxhighlight>
 
The above method has some problems. Most importantly, when given a pair (a,b) with no solution, it generates an FP exception. When given <tt>b=1</tt>, it returns 1 which is not a valid result mod 1. When given negative a or b the results are incorrect. The following generates results that should match Pari/GP for numbers in the int range.
{{trans|Perl}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int mul_inv(int a, int b)
Line 503:
printf("%d\n", mul_inv(40, 2018));
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 514:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">public class Program
{
static void Main()
Line 537:
return x < 0 ? x + m0 : x;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
===Iterative implementation===
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iostream>
int mul_inv(int a, int b)
Line 561:
std::cout << mul_inv(42, 2017) << std::endl;
return 0;
}</langsyntaxhighlight>
 
===Recursive implementation===
<langsyntaxhighlight lang="cpp">#include <iostream>
 
short ObtainMultiplicativeInverse(int a, int b, int s0 = 1, int s1 = 0)
Line 575:
std::cout << ObtainMultiplicativeInverse(42, 2017) << std::endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
 
Line 622:
(println (mul_inv 40 2018))
 
</syntaxhighlight>
</lang>
 
'''Output:'''
Line 635:
=={{header|CLU}}==
{{trans|Perl}}
<langsyntaxhighlight lang="clu">mul_inv = proc (a, b: int) returns (int) signals (no_inverse)
if b<0 then b := -b end
if a<0 then a := b - (-a // b) end
Line 670:
end
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>42, 2017 -> 1969
Line 679:
 
=={{header|Comal}}==
<langsyntaxhighlight lang="comal">0010 FUNC mulinv#(a#,b#) CLOSED
0020 IF b#<0 THEN b#:=-b#
0030 IF a#<0 THEN a#:=b#-(-a# MOD b#)
Line 699:
0190 END
0200 //
0210 DATA 42,2017,40,1,52,-217,-486,217,40,2018</langsyntaxhighlight>
{{out}}
<pre>42, 2017 -> 1969
Line 708:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
;;
;; Calculates the GCD of a and b based on the Extended Euclidean Algorithm. The function also returns
Line 732:
(unless (= 1 r) (error "invmod: Values ~a and ~a are not coprimes." a m))
s))
</syntaxhighlight>
</lang>
 
{{out}}
Line 745:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub mulinv(a: int32, b: int32): (t: int32) is
Line 790:
print_nl();
i := i + 1;
end loop;</langsyntaxhighlight>
{{out}}
<pre>42, 2017 -> 1969
Line 800:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def modinv(a0, m0)
return 1 if m0 == 1
a, m = a0, m0
Line 811:
inv += m0 if inv < 0
inv
end</langsyntaxhighlight>
 
{{out}}
Line 820:
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">T modInverse(T)(T a, T b) pure nothrow {
if (b == 1)
return 1;
Line 842:
import std.stdio;
writeln(modInverse(42, 2017));
}</langsyntaxhighlight>
{{out}}
<pre>1969</pre>
Line 848:
{{trans|C}}
This solution prints the inverse <code>u</code> only if it exists (<code>a*u = 1 mod m</code>).
<syntaxhighlight lang="dc">
<lang dc>
dc -e "[m=]P?dsm[a=]P?dsa1sv[dsb~rsqlbrldlqlv*-lvsdsvd0<x]dsxxldd[dlmr+]sx0>xdla*lm%[p]sx1=x"
</syntaxhighlight>
</lang>
If <code>~</code> is not implemented, it can be replaced by <code>SdSnlnld/LnLd%</code>.
 
Line 878:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc mulinv(int a, b) int:
int t, nt, r, nr, q, tmp;
if b<0 then b := -b fi;
Line 909:
show(-486, 217);
show(40, 2018)
corp</langsyntaxhighlight>
{{out}}
<pre> 42, 2017 -> 1969
Line 918:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; for egcd = extended gcd
 
Line 929:
(mod-inv 42 666)
🔴 error: not-coprimes (42 666)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Modular do
def extended_gcd(a, b) do
{last_remainder, last_x} = extended_gcd(abs(a), abs(b), 1, 0, 0, 1)
Line 953:
end
 
IO.puts Modular.inverse(42,2017)</langsyntaxhighlight>
 
{{out}}
Line 961:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM MOD_INV
 
!$INTEGER
Line 987:
MUL_INV(40,2018->T) PRINT(T)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 998:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Calculate the inverse of a (mod m)
// See here for eea specs:
Line 1,010:
eea t' (t - div * t') r' (r - div * r')
(m + eea 0 1 m a) % m
</syntaxhighlight>
</lang>
{{in}}
<pre>
Line 1,022:
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USE: math.functions
42 2017 mod-inv</langsyntaxhighlight>
{{out}}
<pre>
Line 1,031:
=={{header|Forth}}==
ANS Forth with double-number word set
<langsyntaxhighlight lang="forth">
: invmod { a m | v b c -- inv }
m to v
Line 1,042:
repeat b m mod dup to b 0<
if m b + else b then ;
</syntaxhighlight>
</lang>
ANS Forth version without locals
<langsyntaxhighlight lang="forth">
: modinv ( a m - inv)
dup 1- \ a m (m != 1)?
Line 1,063:
nip \ inv
;
</syntaxhighlight>
</lang>
<pre>
42 2017 invmod . 1969
Line 1,070:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 10-07-2018
' compile with: fbc -s console
 
Line 1,144:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>a * 42 + b * 2017 = GCD(42, 2017) = 1
Line 1,166:
 
=={{header|Frink}}==
<syntaxhighlight lang ="frink">println[modInverse[42, 2017]]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,173:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import integers.egcd
 
def modinv( a, m ) =
Line 1,184:
if res < 0 then res + m else res
 
println( modinv(42, 2017) )</langsyntaxhighlight>
 
{{out}}
Line 1,194:
=={{header|Go}}==
The standard library function uses the extended Euclidean algorithm internally.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,206:
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,215:
{{trans|Pascal}}
{{works with|PC-BASIC|any}}
<langsyntaxhighlight lang="qbasic">
10 ' Modular inverse
20 LET E% = 42
Line 1,243:
1140 LET MODINV% = D%
1150 RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,250:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">-- Given a and m, return Just x such that ax = 1 mod m.
-- If there is no such x return Nothing.
modInv :: Int -> Int -> Maybe Int
Line 1,274:
 
main :: IO ()
main = mapM_ print [2 `modInv` 4, 42 `modInv` 2017]</langsyntaxhighlight>
{{out}}
<pre>Nothing
Line 1,281:
=={{header|Icon}} and {{header|Unicon}}==
{{trans|C}}
<langsyntaxhighlight lang="unicon">procedure main(args)
a := integer(args[1]) | 42
b := integer(args[2]) | 2017
Line 1,296:
}
return if (x1 > 0) then x1 else x1+b0
end</langsyntaxhighlight>
 
{{out}}
Line 1,307:
Adding a coprime test:
 
<langsyntaxhighlight lang="unicon">link numbers
 
procedure main(args)
Line 1,325:
}
return if (x1 > 0) then x1 else x1+b0
end</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PRINT MODINV(42,2017)
120 DEF MODINV(A,B)
130 LET B=ABS(B)
Line 1,345:
260 LET MODINV=T
270 END IF
280 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution''':<langsyntaxhighlight lang="j"> modInv =: dyad def 'x y&|@^ <: 5 p: y'"0</langsyntaxhighlight>
'''Example''':<langsyntaxhighlight lang="j"> 42 modInv 2017
1969</langsyntaxhighlight>
'''Notes''':
 
Line 1,361:
=={{header|Java}}==
The <code>BigInteger</code> library has a method for this:
<langsyntaxhighlight lang="java">System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));</langsyntaxhighlight>
{{out}}
<pre>1969</pre>
Line 1,367:
=={{header|JavaScript}}==
Using brute force.
<langsyntaxhighlight lang="javascript">var modInverse = function(a, b) {
a %= b;
for (var x = 1; x < b; x++) {
Line 1,374:
}
}
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,380:
'''Works with gojq, the Go implementation of jq'''
 
<langsyntaxhighlight lang="jq"># Integer division:
# If $j is 0, then an error condition is raised;
# otherwise, assuming infinite-precision integer arithmetic,
Line 1,416:
# Example:
42 | modInv(2017)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,427:
===Built-in===
Julia includes a built-in function for this:
<syntaxhighlight lang ="julia">invmod(a, b)</langsyntaxhighlight>
 
===C translation===
Line 1,433:
The following code works on any integer type.
To maximize performance, we ensure (via a promotion rule) that the operands are the same type (and use built-ins <code>zero(T)</code> and <code>one(T)</code> for initialization of temporary variables to ensure that they remain of the same type throughout execution).
<langsyntaxhighlight lang="julia">function modinv{T<:Integer}(a::T, b::T)
b0 = b
x0, x1 = zero(T), one(T)
Line 1,443:
x1 < 0 ? x1 + b0 : x1
end
modinv(a::Integer, b::Integer) = modinv(promote(a,b)...)</langsyntaxhighlight>
 
{{out}}
Line 1,455:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.math.BigInteger
Line 1,463:
val m = BigInteger.valueOf(2017)
println(a.modInverse(m))
}</langsyntaxhighlight>
 
{{out}}
Line 1,471:
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(AA, BB)
ENTRY TO MULINV.
Line 1,508:
SHOW.(-486,217)
SHOW.(40,2018)
END OF PROGRAM</langsyntaxhighlight>
{{out}}
<pre> 42, 2017: 1969
Line 1,518:
=={{header|Maple}}==
 
<syntaxhighlight lang="maple">
<lang Maple>
1/42 mod 2017;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,528:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The built-in function <code>FindInstance</code> works well for this
<langsyntaxhighlight Mathematicalang="mathematica">modInv[a_, m_] :=
Block[{x,k}, x /. FindInstance[a x == 1 + k m, {x, k}, Integers]]</langsyntaxhighlight>
 
Another way by using the built-in function <code>PowerMod</code> :
<syntaxhighlight lang Mathematica="mathematica">PowerMod[a,-1,m]</langsyntaxhighlight>
For example :
<pre>modInv[42, 2017]
Line 1,540:
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 П2 <-> П0 0 П5 1 П6 ИП1 1
- x=0 14 С/П ИП0 1 - /-/ x<0 50
ИП0 ИП1 / [x] П4 ИП1 П3 ИП0 ^ ИП1
/ [x] ИП1 * - П1 ИП3 П0 ИП5 П3
ИП6 ИП4 ИП5 * - П5 ИП3 П6 БП 14
ИП6 x<0 55 ИП2 + С/П</langsyntaxhighlight>
 
=={{header|Modula-2}}==
{{trans|C}}
<langsyntaxhighlight Modulalang="modula-2">MODULE ModularInverse;
FROM InOut IMPORT WriteString, WriteInt, WriteLn;
 
Line 1,591:
WriteLn;
END;
END ModularInverse.</langsyntaxhighlight>
{{out}}
<pre>Modular inverse
Line 1,601:
 
=={{header|newLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLisp>
(define (modular-multiplicative-inverse a n)
(if (< n 0)
Line 1,632:
 
(println (modular-multiplicative-inverse 42 2017))
</syntaxhighlight>
</lang>
 
Output:
Line 1,641:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">proc modInv(a0, b0: int): int =
var (a, b, x0) = (a0, b0, 0)
result = 1
Line 1,652:
if result < 0: result += b0
 
echo modInv(42, 2017)</langsyntaxhighlight>
 
{{out}}
Line 1,660:
 
==={{trans|C}}===
<langsyntaxhighlight lang="ocaml">let mul_inv a = function 1 -> 1 | b ->
let rec aux a b x0 x1 =
if a <= 1 then x1 else
Line 1,667:
in
let x = aux a b 0 1 in
if x < 0 then x + b else x</langsyntaxhighlight>
 
Testing:
Line 1,677:
==={{trans|Haskell}}===
 
<langsyntaxhighlight lang="ocaml">let rec gcd_ext a = function
| 0 -> (1, 0, a)
| b ->
Line 1,687:
match gcd_ext a m with
| i, _, 1 -> mk_pos i
| _ -> failwith "mod_inv"</langsyntaxhighlight>
 
Testing:
Line 1,699:
Usage : a modulus invmod
 
<langsyntaxhighlight Oforthlang="oforth">// euclid ( a b -- u v r )
// Return r = gcd(a, b) and (u, v) / r = au + bv
 
Line 1,720:
: invmod(a, modulus)
a modulus euclid 1 == ifFalse: [ drop drop null return ]
drop dup 0 < ifTrue: [ modulus + ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,729:
 
=={{header|PARI/GP}}==
<syntaxhighlight lang ="parigp">Mod(1/42,2017)</langsyntaxhighlight>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang Pascal>
// increments e step times until bal is greater than t
// repeats until bal = 1 (mod = 1) and returns count
Line 1,756:
end;
modInv := d;
end;</langsyntaxhighlight>
 
Testing:
Line 1,767:
=={{header|Perl}}==
Various CPAN modules can do this, such as:
<langsyntaxhighlight lang="perl">use bigint; say 42->bmodinv(2017);
# or
use Math::ModInt qw/mod/; say mod(42, 2017)->inverse->residue;
Line 1,775:
use Math::GMP qw/:constant/; say 42->bmodinv(2017);
# or
use ntheory qw/invmod/; say invmod(42, 2017);</langsyntaxhighlight>
or we can write our own:
<langsyntaxhighlight lang="perl">sub invmod {
my($a,$n) = @_;
my($t,$nt,$r,$nr) = (0, 1, $n, $a % $n);
Line 1,791:
}
 
say invmod(42,2017);</langsyntaxhighlight>
'''Notes''': Special cases to watch out for include (1) where the inverse doesn't exist, such as invmod(14,28474), which should return undef or raise an exception, not return a wrong value. (2) the high bit of a or n is set, e.g. invmod(11,2**63), (3) negative first arguments, e.g. invmod(-11,23).
The modules and code above handle these cases,
Line 1,798:
=={{header|Phix}}==
{{trans|C}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">mul_inv</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">n</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
Line 1,819:
<span style="color: #0000FF;">?</span><span style="color: #000000;">mul_inv</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">486</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">217</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mul_inv</span><span style="color: #0000FF;">(</span><span style="color: #000000;">40</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2018</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,831:
=={{header|PHP}}==
'''Algorithm Implementation'''
<langsyntaxhighlight lang="php"><?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
Line 1,846:
}
printf("%d\n", invmod(42, 2017));
?></langsyntaxhighlight>
{{Out}}
<pre>1969</pre>
Line 1,852:
=={{header|PicoLisp}}==
{{trans|C}}
<langsyntaxhighlight PicoLisplang="picolisp">(de modinv (A B)
(let (B0 B X0 0 X1 1 Q 0 T1 0)
(while (< 1 A)
Line 1,868:
(modinv 42 2017) )
 
(bye)</langsyntaxhighlight>
 
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
/*--------------------------------------------------------------------
* 13.07.2015 Walter Pachl
Line 1,904:
Return(d);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>modular inverse of 42 by 2017 ---> 1969</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function invmod($a,$n){
if ([int]$n -lt 0) {$n = -$n}
if ([int]$a -lt 0) {$a = $n - ((-$a) % $n)}
Line 1,931:
}
 
invmod 42 2017</langsyntaxhighlight>
{{Out}}
<pre>PS> .\INVMOD.PS1
Line 1,938:
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">
<lang Prolog>
egcd(_, 0, 1, 0) :- !.
egcd(A, B, X, Y) :-
Line 1,949:
A*X + B*Y =:= 1,
N is X mod B.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,961:
=={{header|PureBasic}}==
Using brute force.
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Declare main()
Declare.i mi(a.i, b.i)
Line 1,997:
If x > y - 1 : x = -1 : EndIf
ProcedureReturn x
EndProcedure</langsyntaxhighlight>
{{out}}
<pre> MODULAR-INVERSE( 42, 2017) = 1969
Line 2,009:
===Iteration and error-handling===
Implementation of this [http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 pseudocode] with [https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm#Modular_inverse this].
<langsyntaxhighlight lang="python">>>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
Line 2,026:
>>> modinv(42, 2017)
1969
>>> </langsyntaxhighlight>
 
===Recursion and an option type===
Or, using functional composition as an alternative to iterative mutation, and wrapping the resulting value in an option type, to allow for the expression of computations which establish the '''absence''' of a modular inverse:
 
<langsyntaxhighlight lang="python">from functools import (reduce)
from itertools import (chain)
 
Line 2,121:
 
# MAIN ---
main()</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,130:
{{trans|Forth}}
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup 1 != if
[ tuck 1 0
[ swap temp put
Line 2,146:
nip ] is modinv ( n n --> n )
 
42 2017 modinv echo</langsyntaxhighlight>
 
{{out}}
Line 2,153:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
(require math)
(modular-inverse 42 2017)
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
1969
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub inverse($n, :$modulo) {
my ($c, $d, $uc, $vc, $ud, $vd) = ($n % $modulo, $modulo, 1, 0, 0, 1);
my $q;
Line 2,174:
}
 
say inverse 42, :modulo(2017)</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the modular inverse of an integer X modulo Y.*/
parse arg x y . /*obtain two integers from the C.L. */
if x=='' | x=="," then x= 42 /*Not specified? Then use the default.*/
Line 2,193:
 
if $<0 then $= $ + ob /*Negative? Then add the original B. */
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs of: &nbsp; &nbsp; <tt> 42 &nbsp; 2017 </tt>}}
<pre>
Line 2,200:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "42 %! 2017 = " + multInv(42, 2017) + nl
 
Line 2,219:
if multInv < 0 multInv = multInv + b0 ok
return multInv
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,226:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">#based on pseudo code from http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 and from translating the python implementation.
def extended_gcd(a, b)
last_remainder, remainder = a.abs, b.abs
Line 2,245:
end
x % et
end</langsyntaxhighlight>
<pre>
> invmod(42,2017)
Line 2,251:
 
Simplified equivalent implementation
<langsyntaxhighlight lang="ruby">
def modinv(a, m) # compute a^-1 mod m if possible
raise "NO INVERSE - #{a} and #{m} not coprime" unless a.gcd(m) == 1
Line 2,264:
inv
end
</syntaxhighlight>
</lang>
<pre>
> modinv(42,2017)
Line 2,271:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">print multInv(42, 2017)
end
 
Line 2,289:
if multInv < 0 then multInv = multInv + b0
[endFun]
end function</langsyntaxhighlight>
 
{{out}}
Line 2,297:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn mod_inv(a: isize, module: isize) -> isize {
let mut mn = (module, a);
let mut xy = (0, 1);
Line 2,314:
fn main() {
println!("{}", mod_inv(42, 2017))
}</langsyntaxhighlight>
 
{{out}}
Line 2,322:
 
Alternative implementation
<langsyntaxhighlight lang="rust">
fn modinv(a0: isize, m0: isize) -> isize {
if m0 == 1 { return 1 }
Line 2,341:
fn main() {
println!("{}", modinv(42, 2017))
}</langsyntaxhighlight>
 
{{out}}
Line 2,350:
=={{header|Scala}}==
Based on the ''Handbook of Applied Cryptography'', Chapter 2. See http://cacr.uwaterloo.ca/hac/ .
<langsyntaxhighlight lang="scala">
def gcdExt(u: Int, v: Int): (Int, Int, Int) = {
@tailrec
Line 2,365:
val (i, j, g) = gcdExt(a, m)
if (g == 1) Option(if (i < 0) i + m else i) else Option.empty
}</langsyntaxhighlight>
 
Translated from C++ (on this page)
<langsyntaxhighlight lang="scala">
def modInv(a: Int, m: Int, x:Int = 1, y:Int = 0) : Int = if (m == 0) x else modInv(m, a%m, y, x - y*(a/m))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,387:
If a and b are not coprime (gcd(a, b) <> 1) the exception RANGE_ERROR is raised.
 
<langsyntaxhighlight lang="seed7">const func bigInteger: modInverse (in var bigInteger: a,
in var bigInteger: b) is func
result
Line 2,429:
raise RANGE_ERROR;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#modInverse]
Line 2,435:
=={{header|Sidef}}==
Built-in:
<syntaxhighlight lang ="ruby">say 42.modinv(2017)</langsyntaxhighlight>
 
Algorithm implementation:
<langsyntaxhighlight lang="ruby">func invmod(a, n) {
var (t, nt, r, nr) = (0, 1, n, a % n)
while (nr != 0) {
Line 2,450:
}
 
say invmod(42, 2017)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,458:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension BinaryInteger {
@inlinable
public func modInv(_ mod: Self) -> Self {
Line 2,477:
}
 
print(42.modInv(2017))</langsyntaxhighlight>
 
{{out}}
Line 2,485:
=={{header|Tcl}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="tcl">proc gcdExt {a b} {
if {$b == 0} {
return [list 1 0 $a]
Line 2,501:
while {$i < 0} {incr i $m}
return $i
}</langsyntaxhighlight>
Demonstrating
<langsyntaxhighlight lang="tcl">puts "42 %! 2017 = [modInv 42 2017]"
catch {
puts "2 %! 4 = [modInv 2 4]"
} msg; puts $msg</langsyntaxhighlight>
{{out}}
<pre>
Line 2,515:
=={{header|Tiny BASIC}}==
2017 causes integer overflow, so I'll do the inverse of 42 modulo 331 instead.
<langsyntaxhighlight lang="tinybasic">
PRINT "Modular inverse."
PRINT "What is the modulus?"
Line 2,533:
LET B = B - M
GOTO 30
</syntaxhighlight>
</lang>
{{out}}
<pre>Modular inverse.
Line 2,545:
Another version:
{{trans|GW-BASIC}}
<langsyntaxhighlight lang="tinybasic">
REM Modular inverse
LET E=42
Line 2,573:
130 LET M=D
RETURN
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,580:
 
=={{header|tsql}}==
<langsyntaxhighlight lang="tsql">;WITH Iterate(N,A,B,X0,X1)
AS (
SELECT
Line 2,613:
)
SELECT *
FROM ModularInverse</langsyntaxhighlight>
 
== {{header|TypeScript}} ==
{{trans|Pascal}}
<langsyntaxhighlight lang="javascript">
// Modular inverse
 
Line 2,637:
 
console.log(`${modInv(42, 2017)}`); // 1969
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,645:
=={{header|uBasic/4tH}}==
{{trans|C}}
<syntaxhighlight lang="text">Print FUNC(_MulInv(42, 2017))
End
 
Line 2,669:
 
If g@ < 0 Then g@ = g@ + c@
Return (g@)</langsyntaxhighlight>
{{trans|Perl}}
<syntaxhighlight lang="text">Print FUNC(_mul_inv(42, 2017))
Print FUNC(_mul_inv(40, 1))
Print FUNC(_mul_inv(52, -217))
Line 2,694:
If (e@ > 1) Return (-1) ' No inverse'
If (c@ < 0) c@ = c@ + b@
Return (c@)</langsyntaxhighlight>
{{out}}
<pre>1969
Line 2,708:
{{works with|Korn Shell}}
{{works with|Zsh}}
{{trans|PowerShell}}<langsyntaxhighlight lang="sh">function invmod {
typeset -i a=$1 n=$2
if (( n < 0 )); then (( n = -n )); fi
Line 2,731:
}
 
invmod 42 2017</langsyntaxhighlight>
 
{{Out}}
Line 2,737:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">
Private Function mul_inv(a As Long, n As Long) As Variant
If n < 0 Then n = -n
Line 2,768:
Debug.Print mul_inv(-486, 217)
Debug.Print mul_inv(40, 2018)
End Sub</langsyntaxhighlight>{{out}}
<pre> 1969
0
Line 2,777:
=={{header|Wren}}==
{{libheader|Wren-big}}
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
 
var a = BigInt.new(42)
var b = BigInt.new(2017)
System.print(a.modInv(b))</langsyntaxhighlight>
 
{{out}}
Line 2,789:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code IntOut=11, Text=12;
int X;
def A=42, M=2017;
Line 2,795:
if rem(A*X/M) = 1 then [IntOut(0, X); exit];
Text(0, "Does not exist");
]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,803:
=={{header|zkl}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="zkl">fcn gcdExt(a,b){
if(b==0) return(1,0,a);
q,r:=a.divr(b); s,t,g:=gcdExt(b,r); return(t,s-q*t,g);
}
fcn modInv(a,m){i,_,g:=gcdExt(a,m); if(g==1) {if(i<0)i+m} else Void}</langsyntaxhighlight>
divr(a,b) is [integer] (a/b,remainder)
{{out}}
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.