How to calculate 100000! or more in Rust?

Viewed 466

A function for calculating factorial is as follows. But it is clear that usize is not big enough?

fn main() {
    println!("{}", factorial(100000));
}
fn factorial(n: usize) -> usize {
    (1..n+1).fold(1, |a, b| a * b)
}

error message: thread 'main' panicked at 'attempt to multiply with overflow'

Later I planned to use recursion to calculate factorial, but the result was inf

fn factorial(num: f64) -> f64 {
    match num {
        0.0 => 1.0,
        1.0 => 1.0,
        _ => factorial(num - 1.0) * num,
    }
}
1 Answers

You can use BigUint for example:

use num::{BigUint, One};

fn factorial(n: usize) -> BigUint {
    (1..=n).fold(BigUint::one(), |a, b| a * b)
}

Playground

Related