omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / perfect-totient-numbers / perfect-totient-numbers.om
| 1 | note Rosetta Code task "Perfect totient numbers": https://rosettacode.org/wiki/Perfect_totient_numbers |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text first "first 20 perfect totient numbers:" |
| 7 | note ph n is Euler's totient for n below 6000 (the 20th perfect totient number is 5571) |
| 8 | global ph ulong 6000 |
| 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 sieve to void |
| 36 | for i ulong 6000 |
| 37 | put ph i i |
| 38 | end |
| 39 | p = ulong 2 |
| 40 | while lt p 6000 bound 6000 |
| 41 | if eq get ph p p |
| 42 | j = p |
| 43 | while lt j 6000 bound 6000 |
| 44 | put ph j sub get ph j div get ph j p |
| 45 | j = add j p |
| 46 | end |
| 47 | end |
| 48 | p = add p 1 |
| 49 | end |
| 50 | end |
| 51 | note n is perfect totient when phi(n) + phi(phi(n)) + ... down to 1 adds up to n; each step at least halves |
| 52 | note an even value, so 64 steps are plenty |
| 53 | fn main to int |
| 54 | sieve |
| 55 | emit first |
| 56 | c = ulong 0 |
| 57 | n = ulong 2 |
| 58 | while lt c 20 bound 5999 |
| 59 | s = ulong 0 |
| 60 | v = get ph n |
| 61 | while gt v 1 bound 64 |
| 62 | s = add s v |
| 63 | v = get ph v |
| 64 | end |
| 65 | s = add s 1 |
| 66 | if eq s n |
| 67 | emit sp |
| 68 | emitu n |
| 69 | c = add c 1 |
| 70 | end |
| 71 | n = add n 1 |
| 72 | end |
| 73 | emit nl |
| 74 | ret 0 |
| 75 | end |