interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / least-common-multiple / least-common-multiple.om

85 lines · 1512 bytes Raw Blame History
1note Rosetta Code task "Least common multiple": https://rosettacode.org/wiki/Least_common_multiple
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text pre "lcm("
6text cm ", "
7text eqs ") = "
8text tup "lcm(1.."
9note emit writes every byte of a to stdout; a short write is retried, an error exits 1
10fn emit a view uchar * to void
11o = ulong 0
12while lt o len a bound 4096
13k = write 1 a o sub len a o
14if le k 0
15exit 1
16end
17o = add o ulong k
18end
19end
20note emitu writes n in decimal; 20 digits hold every ulong
21fn emitu n ulong to void
22d = new uchar 20 0
23i = ulong 20
24v = n
25while true bound 20
26i = sub i 1
27put d i uchar add rem v 10 48
28v = div v 10
29if eq v 0
30break
31end
32end
33emit part d i sub 20 i
34end
35note Euclid: each two steps at least halve x, so 128 steps cover any 64-bit pair
36fn gcd a ulong b ulong to ulong
37x = a
38y = b
39while ne y 0 bound 128
40t = rem x y
41x = y
42y = t
43end
44ret x
45end
46note lcm(a, b) = a / gcd(a, b) * b, dividing first so the product never exceeds the result
47fn lcm a ulong b ulong to ulong
48if or eq a 0 eq b 0
49ret 0
50end
51ret mul div a gcd a b b
52end
53fn tell a ulong b ulong to void
54emit pre
55emitu a
56emit cm
57emitu b
58emit eqs
59emitu lcm a b
60emit nl
61end
62note lcm of 1..n by folding; lcm(1..40) = 5342931457063200 is below 2^64
63fn upto n ulong to void
64r = ulong 1
65k = ulong 1
66while le k n bound 40
67r = lcm r k
68k = add k 1
69end
70emit tup
71emitu n
72emit eqs
73emitu r
74emit nl
75end
76fn main to int
77tell 12 18
78tell 35 0
79tell 0 5
80tell 4294967296 6000000000
81upto 10
82upto 20
83upto 40
84ret 0
85end