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/tasks/modular-inverse/modular-inverse.om # 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 / tasks / modular-inverse / modular-inverse.om` 93 lines ยท 1623 bytes Raw Blame History 1 note Rosetta Code task "Modular inverse": https://rosettacode.org/wiki/Modular_inverse 2 note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 3 om2 4 text nl "\n" 5 text inv "^-1 mod " 6 text eqs " = " 7 text none " does not exist\n" 8 note emit writes every byte of a to stdout; a short write is retried, an error exits 1 9 fn emit a view uchar * to void 10 o = ulong 0 11 while lt o len a bound 4096 12 k = write 1 a o sub len a o 13 if le k 0 14 exit 1 15 end 16 o = add o ulong k 17 end 18 end 19 note emitu writes n in decimal; 20 digits hold every ulong 20 fn emitu n ulong to void 21 d = new uchar 20 0 22 i = ulong 20 23 v = n 24 while true bound 20 25 i = sub i 1 26 put d i uchar add rem v 10 48 27 v = div v 10 28 if eq v 0 29 break 30 end 31 end 32 emit part d i sub 20 i 33 end 34 note emiti writes a signed n in decimal; the minimum long is turned positive as (-(n+1))+1 in ulong 35 fn emiti n long to void 36 m = new uchar 1 45 37 if lt n 0 38 emit m 39 emitu add ulong neg add n 1 1 40 else 41 emitu ulong n 42 end 43 end 44 note minv: extended Euclid on (m, a mod m) for m > 0; returns -1 when gcd(a, m) > 1 45 note bound: Euclid on values below 2^31 takes fewer than 50 steps; q * nt and q * nr stay below m in size 46 fn minv a long m long to long 47 x = rem a m 48 if lt x 0 49 x = add x m 50 end 51 t = long 0 52 nt = long 1 53 r = m 54 nr = x 55 while ne nr 0 bound 100 56 q = div r nr 57 k = sub t mul q nt 58 t = nt 59 nt = k 60 k = sub r mul q nr 61 r = nr 62 nr = k 63 end 64 if gt r 1 65 ret -1 66 end 67 if lt t 0 68 t = add t m 69 end 70 ret t 71 end 72 fn tell a long m long to void 73 emiti a 74 emit inv 75 emiti m 76 v = minv a m 77 if lt v 0 78 emit none 79 else 80 emit eqs 81 emiti v 82 emit nl 83 end 84 end 85 fn main to int 86 tell 42 2017 87 tell 40 1 88 tell 52 217 89 tell -486 217 90 tell 40 2018 91 tell `1234567` `1000000007` 92 ret 0 93 end