Skip to main content

lib_jsl_special_functions/
factorial.rs

1//! Factorial.
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::{gamma, ln_gamma};
6
7/// Largest `n` for which `n!` fits in a `u64`.
8pub const MAX_U64_FACTORIAL: u64 = 20;
9
10/// Returns `n!` if it fits in a `u64`, otherwise `None`.
11pub fn factorial_checked(n: u64) -> Option<u64> {
12    (2..=n).try_fold(1u64, |acc, k| acc.checked_mul(k))
13}
14
15/// Returns `n!`.
16///
17/// # Panics
18/// Panics if `n > 20`, since `21!` overflows a `u64`. Use [`factorial_f64`] or
19/// [`ln_factorial`] for larger arguments.
20pub fn factorial(n: u64) -> u64 {
21    factorial_checked(n).unwrap_or_else(|| panic!("factorial({n}) overflows u64 (max n is 20)"))
22}
23
24/// Returns `n!` as an `f64` (infinite for `n > 170`).
25pub fn factorial_f64(n: u64) -> f64 {
26    if n > 170 {
27        f64::INFINITY
28    } else {
29        gamma(n as f64 + 1.0)
30    }
31}
32
33/// Returns `ln(n!)`.
34pub fn ln_factorial(n: u64) -> f64 {
35    ln_gamma(n as f64 + 1.0)
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn small_values() {
44        assert_eq!(factorial(0), 1);
45        assert_eq!(factorial(1), 1);
46        assert_eq!(factorial(10), 3_628_800);
47        assert_eq!(factorial(20), 2_432_902_008_176_640_000);
48    }
49
50    #[test]
51    fn overflow() {
52        assert_eq!(factorial_checked(21), None);
53        assert!(std::panic::catch_unwind(|| factorial(21)).is_err());
54    }
55
56    #[test]
57    fn float_and_log() {
58        assert_eq!(factorial_f64(5), 120.0);
59        assert!((factorial_f64(25) / 1.5511210043330986e25 - 1.0).abs() < 1e-14);
60        assert!(factorial_f64(171).is_infinite());
61        assert!((ln_factorial(100) - 363.73937555556347).abs() < 1e-11);
62    }
63}