omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / factors-of-an-integer / factors-of-an-integer.om
| 1 | note Rosetta Code task "Factors of an integer": https://rosettacode.org/wiki/Factors_of_an_integer |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text sp " " |
| 6 | text pre "factors of " |
| 7 | text col ":" |
| 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 divisors d with d * d <= n come out ascending; their partners n / d, read back in reverse, finish the list |
| 35 | note bound: the largest n here is 600851475143, so d stays below 775147, and no n has more than 64 small divisors |
| 36 | fn tell n ulong to void |
| 37 | lo = new ulong 64 0 |
| 38 | k = ulong 0 |
| 39 | d = ulong 1 |
| 40 | while le mul d d n bound 999999 |
| 41 | if eq rem n d 0 |
| 42 | put lo k d |
| 43 | k = add k 1 |
| 44 | end |
| 45 | d = add d 1 |
| 46 | end |
| 47 | emit pre |
| 48 | emitu n |
| 49 | emit col |
| 50 | for i ulong k |
| 51 | emit sp |
| 52 | emitu get lo i |
| 53 | end |
| 54 | for i ulong k |
| 55 | e = get lo sub sub k 1 i |
| 56 | if ne mul e e n |
| 57 | emit sp |
| 58 | emitu div n e |
| 59 | end |
| 60 | end |
| 61 | emit nl |
| 62 | end |
| 63 | fn main to int |
| 64 | tell 1 |
| 65 | tell 45 |
| 66 | tell 53 |
| 67 | tell 64 |
| 68 | tell 720 |
| 69 | tell 1000000 |
| 70 | tell 600851475143 |
| 71 | ret 0 |
| 72 | end |