omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / evaluate-binomial-coefficients / evaluate-binomial-coefficients.om
| 1 | note Rosetta Code task "Evaluate binomial coefficients": https://rosettacode.org/wiki/Evaluate_binomial_coefficients |
| 2 | note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | om2 |
| 4 | text nl "\n" |
| 5 | text cc "C(" |
| 6 | text cm ", " |
| 7 | text eqs ") = " |
| 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 gcd a ulong b ulong to ulong |
| 35 | x = a |
| 36 | y = b |
| 37 | while ne y 0 bound 128 |
| 38 | t = rem x y |
| 39 | x = y |
| 40 | y = t |
| 41 | end |
| 42 | ret x |
| 43 | end |
| 44 | note r runs through C(n-k+i, i) for i = 1..k; with g = gcd(r, i), i / g divides n - k + i, so |
| 45 | note r / g * ((n-k+i) / (i / g)) is exact and never exceeds the final value, which must fit 64 bits |
| 46 | fn binom n ulong k ulong to ulong |
| 47 | r = ulong 1 |
| 48 | for j ulong k |
| 49 | i = add j 1 |
| 50 | g = gcd r i |
| 51 | r = mul div r g div add sub n k i div i g |
| 52 | end |
| 53 | ret r |
| 54 | end |
| 55 | fn tell n ulong k ulong to void |
| 56 | emit cc |
| 57 | emitu n |
| 58 | emit cm |
| 59 | emitu k |
| 60 | emit eqs |
| 61 | emitu binom n k |
| 62 | emit nl |
| 63 | end |
| 64 | fn main to int |
| 65 | tell 5 3 |
| 66 | tell 10 0 |
| 67 | tell 10 10 |
| 68 | tell 33 17 |
| 69 | tell 60 30 |
| 70 | tell 67 33 |
| 71 | ret 0 |
| 72 | end |