问题
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