How to calculate 21 factorial in Rust?

感情迁移 提交于 2020-12-13 18:09:14

问题


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

回答1:


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




回答2:


I need to calculate 21 factorial in my project.

21! doesn't fit in a 64 bit int. You need some arbitrary precision arithmetic (or bigint) library or to implement yours, or use 128 bits ints or some floating point.

According to this list, you could consider using ramp.



来源:https://stackoverflow.com/questions/59206653/how-to-calculate-21-factorial-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!