Search code examples
rustfactorial

How to calculate 21 factorial in Rust?


I need to calculate 21 factorial in my project.

fn factorial(num: u64) -> u64 {
    match num {
        0 => 1,
        1 => 1,
        _ => factorial(num - 1) * num,
    }
}

fn main() {
    let x = factorial(21);
    println!("The value of 21 factorial is {} ", x);
}

When running this code, I get an error:

thread 'main' panicked at 'attempt to multiply with overflow', src\main.rs:5:18

Solution

  • A u64 can’t hold 21! (it’s between 2^65 and 2^66), but a u128 can.