interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / happy-numbers / happy-numbers.om

68 lines · 1309 bytes Raw Blame History
1note Rosetta Code task "Happy numbers": https://rosettacode.org/wiki/Happy_numbers
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text sp " "
6text hdr "first 8 happy numbers:"
7note emit writes every byte of a to stdout; a short write is retried, an error exits 1
8fn emit a view uchar * to void
9o = ulong 0
10while lt o len a bound 4096
11k = write 1 a o sub len a o
12if le k 0
13exit 1
14end
15o = add o ulong k
16end
17end
18note emitu writes n in decimal; 20 digits hold every ulong
19fn emitu n ulong to void
20d = new uchar 20 0
21i = ulong 20
22v = n
23while true bound 20
24i = sub i 1
25put d i uchar add rem v 10 48
26v = div v 10
27if eq v 0
28break
29end
30end
31emit part d i sub 20 i
32end
33fn step n ulong to ulong
34s = ulong 0
35v = n
36while gt v 0 bound 20
37d = rem v 10
38s = add s mul d d
39v = div v 10
40end
41ret s
42end
43note Floyd's tortoise and hare: the iteration is eventually periodic; n is happy when the cycle is 1 -> 1
44note bound: from n < 1000 the values stay below 1000 (a 3-digit square sum is at most 243), so the meeting comes within 1000 steps
45fn happy n ulong to bool
46s = n
47f = step n
48while ne s f bound 1000
49s = step s
50f = step step f
51end
52ret eq s 1
53end
54fn main to int
55emit hdr
56n = ulong 0
57k = ulong 0
58while lt k 8 bound 1000
59n = add n 1
60if happy n
61emit sp
62emitu n
63k = add k 1
64end
65end
66emit nl
67ret 0
68end