omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / drafts / rosettacode / happy-numbers.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 sp " " |
| 8 | text hdr "first 8 happy numbers:" |
| 9 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 10 | fn emit a view uchar * to void |
| 11 | o = ulong 0 |
| 12 | while lt o len a bound 4096 |
| 13 | k = write 1 a o sub len a o |
| 14 | if le k 0 |
| 15 | exit 1 |
| 16 | end |
| 17 | o = add o ulong k |
| 18 | end |
| 19 | end |
| 20 | note emitu writes n in decimal; 20 digits hold every ulong |
| 21 | fn emitu n ulong to void |
| 22 | d = new uchar 20 0 |
| 23 | i = ulong 20 |
| 24 | v = n |
| 25 | while true bound 20 |
| 26 | i = sub i 1 |
| 27 | put d i uchar add rem v 10 48 |
| 28 | v = div v 10 |
| 29 | if eq v 0 |
| 30 | break |
| 31 | end |
| 32 | end |
| 33 | emit part d i sub 20 i |
| 34 | end |
| 35 | fn step n ulong to ulong |
| 36 | s = ulong 0 |
| 37 | v = n |
| 38 | while gt v 0 bound 20 |
| 39 | d = rem v 10 |
| 40 | s = add s mul d d |
| 41 | v = div v 10 |
| 42 | end |
| 43 | ret s |
| 44 | end |
| 45 | note Floyd's tortoise and hare: the iteration is eventually periodic; n is happy when the cycle is 1 -> 1 |
| 46 | note 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 |
| 47 | fn happy n ulong to bool |
| 48 | s = n |
| 49 | f = step n |
| 50 | while ne s f bound 1000 |
| 51 | s = step s |
| 52 | f = step step f |
| 53 | end |
| 54 | ret eq s 1 |
| 55 | end |
| 56 | fn main to int |
| 57 | emit hdr |
| 58 | n = ulong 0 |
| 59 | k = ulong 0 |
| 60 | while lt k 8 bound 1000 |
| 61 | n = add n 1 |
| 62 | if happy n |
| 63 | emit sp |
| 64 | emitu n |
| 65 | k = add k 1 |
| 66 | end |
| 67 | end |
| 68 | emit nl |
| 69 | ret 0 |
| 70 | end |
| 71 | </syntaxhighlight> |
| 72 | {{out}} |
| 73 | <pre> |
| 74 | first 8 happy numbers: 1 7 10 13 19 23 28 31 |
| 75 | </pre> |