RosettaCodeData/Task/Evaluate-binomial-coefficients/Dc/evaluate-binomial-coefficients-3.dc
2017-09-25 22:28:19 +02:00

31 lines
1.3 KiB
Text

[ macro z: factorial base case when n is (z)ero ]sx
[sx [ x is our dump register; get rid of extraneous copy of n we no longer need]sx
1 [ return value is 1 ]sx
q] [ abort processing of calling macro ]sx
sz
[ macro f: factorial ]sx [
d [ duplicate the input (n) ]sx
0 =z [ if n is zero, call z, which stops here and returns 1 ]sx
d [ otherwise, duplicate n again ]sx
1 - [ subtract 1 ]sx
lfx [ take the factorial ]sx
* [ we have (n-1)!; multiply it by the copy of n to get n! ]sx
] sf
[ macro b(n,k): binomial function (n choose k).
straightforward RPN version of formula.]sx [
sk [ remember k. stack: n ]sx
d [ duplicate: n n ]sx
lfx [ call factorial: n n! ]sx
r [ swap: n! n ]sx
lk [ load k: n! n k ]sx
- [ subtract: n! n-k ]sx
lfx [ call factorial: n! (n-k)! ]sx
lk [ load k: n! (n-k)! k ]sx
lfx [ call factorial; n! (n-k)! k! ]sx
* [ multiply: n! (n-k)!k! ]sx
/ [ divide: n!/(n-k)!k! ]sx
] sb
5 3 lb x p [print(5 choose 3)]sx