lib_jsl_special_functions/
binomial_coefficients.rs1use crate::gamma::ln_gamma;
6
7pub 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.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
24pub 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
34pub 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}