Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/omega-rosetta/blob/main/drafts/rosettacode/modular-inverse.wiki
# omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
branch `main` Branches Tags History
`omega-rosetta / drafts / rosettacode / modular-inverse.wiki`
105 lines ยท 1900 bytes Raw Blame History
1 =={{header|Omegese}}==
2 {{works with|omc|sha256 `2c824805`, aien-dev/omega-mv `e5b32567`, Linux AArch64}}
3 Omega has no imports, so the small output helpers (emit and friends) are part of the program.
4
5 om2
6 text nl "\n"
7 text inv "^-1 mod "
8 text eqs " = "
9 text none " does not exist\n"
10 note emit writes every byte of a to stdout; a short write is retried, an error exits 1
11 fn emit a view uchar * to void
12 o = ulong 0
13 while lt o len a bound 4096
14 k = write 1 a o sub len a o
15 if le k 0
16 exit 1
17 end
18 o = add o ulong k
19 end
20 end
21 note emitu writes n in decimal; 20 digits hold every ulong
22 fn emitu n ulong to void
23 d = new uchar 20 0
24 i = ulong 20
25 v = n
26 while true bound 20
27 i = sub i 1
28 put d i uchar add rem v 10 48
29 v = div v 10
30 if eq v 0
31 break
32 end
33 end
34 emit part d i sub 20 i
35 end
36 note emiti writes a signed n in decimal; the minimum long is turned positive as (-(n+1))+1 in ulong
37 fn emiti n long to void
38 m = new uchar 1 45
39 if lt n 0
40 emit m
41 emitu add ulong neg add n 1 1
42 else
43 emitu ulong n
44 end
45 end
46 note minv: extended Euclid on (m, a mod m) for m > 0; returns -1 when gcd(a, m) > 1
47 note bound: Euclid on values below 2^31 takes fewer than 50 steps; q * nt and q * nr stay below m in size
48 fn minv a long m long to long
49 x = rem a m
50 if lt x 0
51 x = add x m
52 end
53 t = long 0
54 nt = long 1
55 r = m
56 nr = x
57 while ne nr 0 bound 100
58 q = div r nr
59 k = sub t mul q nt
60 t = nt
61 nt = k
62 k = sub r mul q nr
63 r = nr
64 nr = k
65 end
66 if gt r 1
67 ret -1
68 end
69 if lt t 0
70 t = add t m
71 end
72 ret t
73 end
74 fn tell a long m long to void
75 emiti a
76 emit inv
77 emiti m
78 v = minv a m
79 if lt v 0
80 emit none
81 else
82 emit eqs
83 emiti v
84 emit nl
85 end
86 end
87 fn main to int
88 tell 42 2017
89 tell 40 1
90 tell 52 217
91 tell -486 217
92 tell 40 2018
93 tell `1234567` `1000000007`
94 ret 0
95 end
96
97 {{out}}
98
99 42^-1 mod 2017 = 1969
100 40^-1 mod 1 = 0
101 52^-1 mod 217 = 96
102 -486^-1 mod 217 = 121
103 40^-1 mod 2018 does not exist
104 `1234567`^-1 mod `1000000007` = `989145189`
105