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