omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / proper-divisors / proper-divisors.om
| 1 | note Rosetta Code task "Proper divisors": https://rosettacode.org/wiki/Proper_divisors |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text col ":" |
| 7 | text most "the number in 1..20000 with the most proper divisors: " |
| 8 | text has " has " |
| 9 | text pd " proper divisors\n" |
| 10 | note nd n counts the proper divisors of n, for n up to 20000 |
| 11 | global nd ulong 20001 |
| 12 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 13 | fn emit a view uchar * to void |
| 14 | o = ulong 0 |
| 15 | while lt o len a bound 4096 |
| 16 | k = write 1 a o sub len a o |
| 17 | if le k 0 |
| 18 | exit 1 |
| 19 | end |
| 20 | o = add o ulong k |
| 21 | end |
| 22 | end |
| 23 | note emitu writes n in decimal; 20 digits hold every ulong |
| 24 | fn emitu n ulong to void |
| 25 | d = new uchar 20 0 |
| 26 | i = ulong 20 |
| 27 | v = n |
| 28 | while true bound 20 |
| 29 | i = sub i 1 |
| 30 | put d i uchar add rem v 10 48 |
| 31 | v = div v 10 |
| 32 | if eq v 0 |
| 33 | break |
| 34 | end |
| 35 | end |
| 36 | emit part d i sub 20 i |
| 37 | end |
| 38 | fn main to int |
| 39 | note proper divisors of 1..10 by trial over 1..n-1 |
| 40 | for i ulong 10 |
| 41 | n = add i 1 |
| 42 | emitu n |
| 43 | emit col |
| 44 | for j ulong i |
| 45 | d = add j 1 |
| 46 | if eq rem n d 0 |
| 47 | emit sp |
| 48 | emitu d |
| 49 | end |
| 50 | end |
| 51 | emit nl |
| 52 | end |
| 53 | note each d counts once for each multiple 2d, 3d, ... up to 20000; fewer than 20000 multiples per d |
| 54 | d = ulong 1 |
| 55 | while le d 10000 bound 10000 |
| 56 | j = mul d 2 |
| 57 | while le j 20000 bound 20000 |
| 58 | put nd j add get nd j 1 |
| 59 | j = add j d |
| 60 | end |
| 61 | d = add d 1 |
| 62 | end |
| 63 | b = ulong 1 |
| 64 | for i ulong 20000 |
| 65 | n = add i 1 |
| 66 | if gt get nd n get nd b |
| 67 | b = n |
| 68 | end |
| 69 | end |
| 70 | emit most |
| 71 | emitu b |
| 72 | emit has |
| 73 | emitu get nd b |
| 74 | emit pd |
| 75 | ret 0 |
| 76 | end |