omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / drafts / rosettacode / least-common-multiple.wiki
| 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 (<code>emit</code> and friends) are part of the program. |
| 4 | <syntaxhighlight lang="text"> |
| 5 | om2 |
| 6 | text nl "\n" |
| 7 | text pre "lcm(" |
| 8 | text cm ", " |
| 9 | text eqs ") = " |
| 10 | text tup "lcm(1.." |
| 11 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 12 | fn emit a view uchar * to void |
| 13 | o = ulong 0 |
| 14 | while lt o len a bound 4096 |
| 15 | k = write 1 a o sub len a o |
| 16 | if le k 0 |
| 17 | exit 1 |
| 18 | end |
| 19 | o = add o ulong k |
| 20 | end |
| 21 | end |
| 22 | note emitu writes n in decimal; 20 digits hold every ulong |
| 23 | fn emitu n ulong to void |
| 24 | d = new uchar 20 0 |
| 25 | i = ulong 20 |
| 26 | v = n |
| 27 | while true bound 20 |
| 28 | i = sub i 1 |
| 29 | put d i uchar add rem v 10 48 |
| 30 | v = div v 10 |
| 31 | if eq v 0 |
| 32 | break |
| 33 | end |
| 34 | end |
| 35 | emit part d i sub 20 i |
| 36 | end |
| 37 | note Euclid: each two steps at least halve x, so 128 steps cover any 64-bit pair |
| 38 | fn gcd a ulong b ulong to ulong |
| 39 | x = a |
| 40 | y = b |
| 41 | while ne y 0 bound 128 |
| 42 | t = rem x y |
| 43 | x = y |
| 44 | y = t |
| 45 | end |
| 46 | ret x |
| 47 | end |
| 48 | note lcm(a, b) = a / gcd(a, b) * b, dividing first so the product never exceeds the result |
| 49 | fn lcm a ulong b ulong to ulong |
| 50 | if or eq a 0 eq b 0 |
| 51 | ret 0 |
| 52 | end |
| 53 | ret mul div a gcd a b b |
| 54 | end |
| 55 | fn tell a ulong b ulong to void |
| 56 | emit pre |
| 57 | emitu a |
| 58 | emit cm |
| 59 | emitu b |
| 60 | emit eqs |
| 61 | emitu lcm a b |
| 62 | emit nl |
| 63 | end |
| 64 | note lcm of 1..n by folding; lcm(1..40) = 5342931457063200 is below 2^64 |
| 65 | fn upto n ulong to void |
| 66 | r = ulong 1 |
| 67 | k = ulong 1 |
| 68 | while le k n bound 40 |
| 69 | r = lcm r k |
| 70 | k = add k 1 |
| 71 | end |
| 72 | emit tup |
| 73 | emitu n |
| 74 | emit eqs |
| 75 | emitu r |
| 76 | emit nl |
| 77 | end |
| 78 | fn main to int |
| 79 | tell 12 18 |
| 80 | tell 35 0 |
| 81 | tell 0 5 |
| 82 | tell 4294967296 6000000000 |
| 83 | upto 10 |
| 84 | upto 20 |
| 85 | upto 40 |
| 86 | ret 0 |
| 87 | end |
| 88 | </syntaxhighlight> |
| 89 | {{out}} |
| 90 | <pre> |
| 91 | lcm(12, 18) = 36 |
| 92 | lcm(35, 0) = 0 |
| 93 | lcm(0, 5) = 0 |
| 94 | lcm(4294967296, 6000000000) = 25165824000000000 |
| 95 | lcm(1..10) = 2520 |
| 96 | lcm(1..20) = 232792560 |
| 97 | lcm(1..40) = 5342931457063200 |
| 98 | </pre> |