【问题标题】:How to calculate 21 factorial in Rust?如何在 Rust 中计算 21 阶乘?
【发布时间】:2019-12-06 03:57:56
【问题描述】:

我需要在我的项目中计算 21 阶乘。

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);
}

运行此代码时,出现错误:

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

【问题讨论】:

    标签: rust factorial


    【解决方案1】:

    u64 无法容纳 21! (介于 2^65 和 2^66 之间),但 u128 可以。

    【讨论】:

      【解决方案2】:

      我需要在我的项目中计算 21 阶乘。

      21!不适合 64 位整数。您需要一些 arbitrary precision arithmetic(或 bigint)库或实现您的库,或使用 128 位整数或浮点数。

      根据this list,可以考虑使用ramp

      【讨论】:

        【解决方案3】:

        一个可能的实现可能是

        pub fn factorial(num: u128) -> u128 {
            match num {
                0  => 1,
                1.. => (1..num+1).product(),
            }
        }
        
        
        #[test]
        fn factorial_of_21() {
           assert_eq!(51090942171709440000,factorial(21));
        }
        
        

        【讨论】:

        • 准时:我们可以用 u128 计算 34! == 295232799039604140847618609643520000000。;-)
        猜你喜欢
        • 2016-06-02
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 1970-01-01
        • 2022-01-17
        相关资源
        最近更新 更多