omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / amicable-pairs / amicable-pairs.om
| 1 | note Rosetta Code task "Amicable pairs": https://rosettacode.org/wiki/Amicable_pairs |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | note ds n is the sum of the proper divisors of n, for n below 20000 |
| 7 | global ds ulong 20000 |
| 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 | note each i adds itself to its multiples 2i, 3i, ... below 20000; fewer than 20000 multiples per i |
| 35 | fn sieve to void |
| 36 | i = ulong 1 |
| 37 | while lt i 10000 bound 10000 |
| 38 | j = mul i 2 |
| 39 | while lt j 20000 bound 20000 |
| 40 | put ds j add get ds j i |
| 41 | j = add j i |
| 42 | end |
| 43 | i = add i 1 |
| 44 | end |
| 45 | end |
| 46 | fn main to int |
| 47 | sieve |
| 48 | for n ulong 20000 |
| 49 | m = get ds n |
| 50 | if and gt m n lt m 20000 |
| 51 | if eq get ds m n |
| 52 | emitu n |
| 53 | emit sp |
| 54 | emitu m |
| 55 | emit nl |
| 56 | end |
| 57 | end |
| 58 | end |
| 59 | ret 0 |
| 60 | end |