簡體   English   中英

如何計算 Rust 的 21 階乘?

[英]How to calculate 21 factorial in Rust?

我需要在我的項目中計算 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

一個u64 21! (它在 2^65 和 2^66 之間),但是u128可以。

我需要在我的項目中計算 21 階乘。

21! 不適合 64 位 int。 您需要一些任意精度算術(或 bigint)庫或實現您的庫,或者使用 128 位整數或一些浮點數。

根據這個列表,你可以考慮使用ramp

一個可能的實現可能是

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

我認為實現應該是這樣的

pub fn factorial(num: u128) -> u128 {
    (1..=num).product()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM