fork/numbat

git clone https://git.julia.blue/fork/numbat

David PeterImprove binomial coeffient example using logical operators6b6d0de

master
745 B20 linesraw
1# Binomial coefficient using Pascal's rule
2#
3# Adapted from the Python version here:
4# https://en.wikipedia.org/wiki/Binomial_coefficient
5
6fn binomial_coefficient(n: Scalar, k: Scalar) -> Scalar =
7    if k < 0 || k > n
8        then 0
9        else if k > n - k # Take advantage of symmetry
10            then binomial_coefficient(n, n - k)
11            else if k == 0 || n <= 1
12                then 1
13                else binomial_coefficient(n - 1, k) + binomial_coefficient(n - 1, k - 1)
14
15assert_eq(binomial_coefficient(10, 0), 1)
16assert_eq(binomial_coefficient(10, 1), 10)
17assert_eq(binomial_coefficient(10, 2), 45)
18assert_eq(binomial_coefficient(10, 6), 210)
19assert_eq(binomial_coefficient(10, 9), 10)
20assert_eq(binomial_coefficient(10, 10), 1)