interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / evaluate-binomial-coefficients / evaluate-binomial-coefficients.om

72 lines · 1346 bytes Raw Blame History
1note Rosetta Code task "Evaluate binomial coefficients": https://rosettacode.org/wiki/Evaluate_binomial_coefficients
2note SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3om2
4text nl "\n"
5text cc "C("
6text cm ", "
7text eqs ") = "
8note emit writes every byte of a to stdout; a short write is retried, an error exits 1
9fn emit a view uchar * to void
10o = ulong 0
11while lt o len a bound 4096
12k = write 1 a o sub len a o
13if le k 0
14exit 1
15end
16o = add o ulong k
17end
18end
19note emitu writes n in decimal; 20 digits hold every ulong
20fn emitu n ulong to void
21d = new uchar 20 0
22i = ulong 20
23v = n
24while true bound 20
25i = sub i 1
26put d i uchar add rem v 10 48
27v = div v 10
28if eq v 0
29break
30end
31end
32emit part d i sub 20 i
33end
34fn gcd a ulong b ulong to ulong
35x = a
36y = b
37while ne y 0 bound 128
38t = rem x y
39x = y
40y = t
41end
42ret x
43end
44note r runs through C(n-k+i, i) for i = 1..k; with g = gcd(r, i), i / g divides n - k + i, so
45note r / g * ((n-k+i) / (i / g)) is exact and never exceeds the final value, which must fit 64 bits
46fn binom n ulong k ulong to ulong
47r = ulong 1
48for j ulong k
49i = add j 1
50g = gcd r i
51r = mul div r g div add sub n k i div i g
52end
53ret r
54end
55fn tell n ulong k ulong to void
56emit cc
57emitu n
58emit cm
59emitu k
60emit eqs
61emitu binom n k
62emit nl
63end
64fn main to int
65tell 5 3
66tell 10 0
67tell 10 10
68tell 33 17
69tell 60 30
70tell 67 33
71ret 0
72end