omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / drafts / rosettacode / evaluate-binomial-coefficients.wiki
| 1 | =={{header|Omegese}}== |
| 2 | {{works with|omc|sha256 2c824805, aien-dev/omega-mv e5b32567, Linux AArch64}} |
| 3 | Omega has no imports, so the small output helpers (<code>emit</code> and friends) are part of the program. |
| 4 | <syntaxhighlight lang="text"> |
| 5 | om2 |
| 6 | text nl "\n" |
| 7 | text cc "C(" |
| 8 | text cm ", " |
| 9 | text eqs ") = " |
| 10 | note emit writes every byte of a to stdout; a short write is retried, an error exits 1 |
| 11 | fn emit a view uchar * to void |
| 12 | o = ulong 0 |
| 13 | while lt o len a bound 4096 |
| 14 | k = write 1 a o sub len a o |
| 15 | if le k 0 |
| 16 | exit 1 |
| 17 | end |
| 18 | o = add o ulong k |
| 19 | end |
| 20 | end |
| 21 | note emitu writes n in decimal; 20 digits hold every ulong |
| 22 | fn emitu n ulong to void |
| 23 | d = new uchar 20 0 |
| 24 | i = ulong 20 |
| 25 | v = n |
| 26 | while true bound 20 |
| 27 | i = sub i 1 |
| 28 | put d i uchar add rem v 10 48 |
| 29 | v = div v 10 |
| 30 | if eq v 0 |
| 31 | break |
| 32 | end |
| 33 | end |
| 34 | emit part d i sub 20 i |
| 35 | end |
| 36 | fn gcd a ulong b ulong to ulong |
| 37 | x = a |
| 38 | y = b |
| 39 | while ne y 0 bound 128 |
| 40 | t = rem x y |
| 41 | x = y |
| 42 | y = t |
| 43 | end |
| 44 | ret x |
| 45 | end |
| 46 | 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 |
| 47 | note r / g * ((n-k+i) / (i / g)) is exact and never exceeds the final value, which must fit 64 bits |
| 48 | fn binom n ulong k ulong to ulong |
| 49 | r = ulong 1 |
| 50 | for j ulong k |
| 51 | i = add j 1 |
| 52 | g = gcd r i |
| 53 | r = mul div r g div add sub n k i div i g |
| 54 | end |
| 55 | ret r |
| 56 | end |
| 57 | fn tell n ulong k ulong to void |
| 58 | emit cc |
| 59 | emitu n |
| 60 | emit cm |
| 61 | emitu k |
| 62 | emit eqs |
| 63 | emitu binom n k |
| 64 | emit nl |
| 65 | end |
| 66 | fn main to int |
| 67 | tell 5 3 |
| 68 | tell 10 0 |
| 69 | tell 10 10 |
| 70 | tell 33 17 |
| 71 | tell 60 30 |
| 72 | tell 67 33 |
| 73 | ret 0 |
| 74 | end |
| 75 | </syntaxhighlight> |
| 76 | {{out}} |
| 77 | <pre> |
| 78 | C(5, 3) = 10 |
| 79 | C(10, 0) = 1 |
| 80 | C(10, 10) = 1 |
| 81 | C(33, 17) = 1166803110 |
| 82 | C(60, 30) = 118264581564861424 |
| 83 | C(67, 33) = 14226520737620288370 |
| 84 | </pre> |