omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / sum-multiples-of-3-and-5 / sum-multiples-of-3-and-5.om
| 1 | note Rosetta Code task "Sum multiples of 3 and 5": https://rosettacode.org/wiki/Sum_multiples_of_3_and_5 |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text loop "by loop, below 1000: " |
| 6 | text pre "by formula, below 10^" |
| 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 the multiples of k below n add up to k * m * (m + 1) / 2 with m = (n - 1) / k; inclusion-exclusion |
| 35 | note removes the multiples of 15 counted twice. Below 10^9 every product stays under 2^64 |
| 36 | fn sm k ulong n ulong to ulong |
| 37 | m = div sub n 1 k |
| 38 | ret div mul mul k m add m 1 2 |
| 39 | end |
| 40 | fn main to int |
| 41 | s = ulong 0 |
| 42 | for i ulong 1000 |
| 43 | if or eq rem i 3 0 eq rem i 5 0 |
| 44 | s = add s i |
| 45 | end |
| 46 | end |
| 47 | emit loop |
| 48 | emitu s |
| 49 | emit nl |
| 50 | n = ulong 10 |
| 51 | for e ulong 9 |
| 52 | emit pre |
| 53 | emitu add e 1 |
| 54 | emit col |
| 55 | emitu sub add sm 3 n sm 5 n sm 15 n |
| 56 | emit nl |
| 57 | n = mul n 10 |
| 58 | end |
| 59 | ret 0 |
| 60 | end |