Hi everyone,
What's the idiomatic or preferred way of calculating factorials in Rust? I came across a problem in which I needed to calculate n! * n
without overflowing a usize
variable, so I ended up using the try_fold
function of the Iterator trait with checked multiplications.
fn main() {
let n: usize = 20;
println!("n: {}, usize::MAX: {}", n, usize::MAX);
println!();
let result: Option<usize> = (1..=n)
.try_fold(1, |acc: usize, f: usize| {
let factorial = acc.checked_mul(f);
if let Some(factorial) = factorial {
println!("n!: {}", factorial);
factorial.checked_mul(n)?;
}
factorial
})
.and_then(|factorial| factorial.checked_mul(n));
println!();
if result.is_some() {
println!("n! * n: {}", result.unwrap());
} else {
println!("n! * n overflows a usize");
}
}
I'm wondering if there is a better way of doing this (optimizations are welcome) or if I'm better off using a crate - I only came across this one.