omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / pernicious-numbers / pernicious-numbers.om
| 1 | note Rosetta Code task "Pernicious numbers": https://rosettacode.org/wiki/Pernicious_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 25 pernicious numbers:" |
| 7 | text range "pernicious numbers from 888888877 to 888888888:" |
| 8 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 9 | fn emit a view uchar * to void |
| 10 | o = ulong 0 |
| 11 | while lt o len a bound 4096 |
| 12 | k = write 1 a o sub len a o |
| 13 | if le k 0 |
| 14 | exit 1 |
| 15 | end |
| 16 | o = add o ulong k |
| 17 | end |
| 18 | end |
| 19 | note emitu writes n in decimal; 20 digits hold every ulong |
| 20 | fn emitu n ulong to void |
| 21 | d = new uchar 20 0 |
| 22 | i = ulong 20 |
| 23 | v = n |
| 24 | while true bound 20 |
| 25 | i = sub i 1 |
| 26 | put d i uchar add rem v 10 48 |
| 27 | v = div v 10 |
| 28 | if eq v 0 |
| 29 | break |
| 30 | end |
| 31 | end |
| 32 | emit part d i sub 20 i |
| 33 | end |
| 34 | fn popc n ulong to ulong |
| 35 | c = ulong 0 |
| 36 | v = n |
| 37 | while gt v 0 bound 64 |
| 38 | c = add c and v 1 |
| 39 | v = shr v 1 |
| 40 | end |
| 41 | ret c |
| 42 | end |
| 43 | note a pernicious number has a prime population count; counts here are at most 30, so trial division is enough |
| 44 | fn isprime n ulong to bool |
| 45 | if lt n 2 |
| 46 | ret false |
| 47 | end |
| 48 | d = ulong 2 |
| 49 | while le mul d d n bound 8 |
| 50 | if eq rem n d 0 |
| 51 | ret false |
| 52 | end |
| 53 | d = add d 1 |
| 54 | end |
| 55 | ret true |
| 56 | end |
| 57 | fn main to int |
| 58 | emit first |
| 59 | c = ulong 0 |
| 60 | n = ulong 1 |
| 61 | while lt c 25 bound 100 |
| 62 | if isprime popc n |
| 63 | emit sp |
| 64 | emitu n |
| 65 | c = add c 1 |
| 66 | end |
| 67 | n = add n 1 |
| 68 | end |
| 69 | emit nl |
| 70 | emit range |
| 71 | for i ulong 12 |
| 72 | n = add 888888877 i |
| 73 | if isprime popc n |
| 74 | emit sp |
| 75 | emitu n |
| 76 | end |
| 77 | end |
| 78 | emit nl |
| 79 | ret 0 |
| 80 | end |