pub const WGSL_FACTORIAL_F64: &str = include_str!("../shaders/special/factorial_f64.wgsl");
#[must_use]
pub fn factorial(n: usize) -> f64 {
const FACTORIAL_TABLE: [f64; 21] = [
1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362_880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, 1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, ];
if n <= 20 {
FACTORIAL_TABLE[n]
} else {
let n_f64 = n as f64;
let sqrt_2pi_n = (2.0 * std::f64::consts::PI * n_f64).sqrt();
let n_over_e = n_f64 / std::f64::consts::E;
sqrt_2pi_n * n_over_e.powf(n_f64)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_factorial_small() {
assert_eq!(factorial(0), 1.0);
assert_eq!(factorial(1), 1.0);
assert_eq!(factorial(2), 2.0);
assert_eq!(factorial(3), 6.0);
assert_eq!(factorial(4), 24.0);
assert_eq!(factorial(5), 120.0);
}
#[test]
fn test_factorial_medium() {
assert_eq!(factorial(10), 3628800.0);
assert_eq!(factorial(15), 1307674368000.0);
assert_eq!(factorial(20), 2432902008176640000.0);
}
#[test]
fn test_factorial_large_stirling() {
let f25 = factorial(25);
assert!(f25 > 1e25);
assert!(f25 < 2e25);
assert!(factorial(30) > factorial(25));
assert!(factorial(50) > factorial(30));
}
#[test]
fn test_factorial_stirling_accuracy() {
let f21 = factorial(21);
let expected = 51090942171709440000.0;
let relative_error = (f21 - expected).abs() / expected;
assert!(
relative_error < 0.01,
"Stirling error too large: {} vs {}, error = {:.2}%",
f21,
expected,
relative_error * 100.0
);
}
}