Skip to main content

lib_jsl_special_functions/
binomial_coefficients.rs

1//! Binomial coefficients.
2//!
3//! See the book entry [The gamma function and related functions](https://jwkunz.github.io/lib_jsl/book/special_functions/gamma.html#factorials-and-binomial-coefficients).
4
5use crate::gamma::ln_gamma;
6
7/// Returns C(n, k) if it fits in a `u64`, otherwise `None`. C(n, k) is 0 when `k > n`.
8pub fn binomial_coefficient_checked(n: u64, k: u64) -> Option<u64> {
9    if k > n {
10        return Some(0);
11    }
12    let k = k.min(n - k);
13    let mut result: u128 = 1;
14    for i in 0..k {
15        // result = result * (n - i) / (i + 1) is always an exact integer division.
16        result = result.checked_mul((n - i) as u128)? / (i + 1) as u128;
17        if result > u64::MAX as u128 {
18            return None;
19        }
20    }
21    Some(result as u64)
22}
23
24/// Returns the binomial coefficient C(n, k).
25///
26/// # Panics
27/// Panics if the result does not fit in a `u64`; see [`binomial_coefficient_checked`] and
28/// [`ln_binomial_coefficient`] for alternatives.
29pub fn binomial_coefficient(n: u64, k: u64) -> u64 {
30    binomial_coefficient_checked(n, k)
31        .unwrap_or_else(|| panic!("binomial_coefficient({n}, {k}) overflows u64"))
32}
33
34/// Returns ln C(n, k) (negative infinity when `k > n`).
35pub fn ln_binomial_coefficient(n: u64, k: u64) -> f64 {
36    if k > n {
37        return f64::NEG_INFINITY;
38    }
39    let (n, k) = (n as f64, k as f64);
40    ln_gamma(n + 1.0) - ln_gamma(k + 1.0) - ln_gamma(n - k + 1.0)
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn small() {
49        assert_eq!(binomial_coefficient(5, 2), 10);
50        assert_eq!(binomial_coefficient(10, 0), 1);
51        assert_eq!(binomial_coefficient(10, 10), 1);
52        assert_eq!(binomial_coefficient(3, 5), 0);
53        assert_eq!(binomial_coefficient(52, 5), 2_598_960);
54    }
55
56    #[test]
57    fn large_exact() {
58        assert_eq!(binomial_coefficient(60, 30), 118_264_581_564_861_424);
59        assert_eq!(binomial_coefficient(64, 32), 1_832_624_140_942_590_534);
60    }
61
62    #[test]
63    fn overflow() {
64        assert_eq!(binomial_coefficient_checked(100, 50), None);
65    }
66
67    #[test]
68    fn logarithm() {
69        let want = 100891344545564193334812497256f64.ln();
70        assert!((ln_binomial_coefficient(100, 50) - want).abs() < 1e-11);
71        assert_eq!(ln_binomial_coefficient(3, 5), f64::NEG_INFINITY);
72    }
73}