UNPKG

780 Btext/coffeescriptView Raw
1# Binomial coefficient
2#
3# Input: tos-2 n
4#
5# tos-1 k
6#
7# Output: Binomial coefficient on stack
8#
9# binomial(n, k) = n! / k! / (n - k)!
10#
11# The binomial coefficient vanishes for k < 0 or k > n. (A=B, p. 19)
12
13
14
15
16Eval_binomial = ->
17 push(cadr(p1))
18 Eval()
19 push(caddr(p1))
20 Eval()
21 binomial()
22
23binomial = ->
24 save()
25 ybinomial()
26 restore()
27
28#define N p1
29#define K p2
30
31ybinomial = ->
32 p2 = pop()
33 p1 = pop()
34
35 if (BINOM_check_args() == 0)
36 push(zero)
37 return
38
39 push(p1)
40 factorial()
41
42 push(p2)
43 factorial()
44
45 divide()
46
47 push(p1)
48 push(p2)
49 subtract()
50 factorial()
51
52 divide()
53
54BINOM_check_args = ->
55 if (isnum(p1) && lessp(p1, zero))
56 return 0
57 else if (isnum(p2) && lessp(p2, zero))
58 return 0
59 else if (isnum(p1) && isnum(p2) && lessp(p1, p2))
60 return 0
61 else
62 return 1
63