Implement factorial using generic mathematics
This commit is contained in:
@@ -7,3 +7,4 @@ edition = "2018"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
num-traits = "0.2"
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
fn fact(x: u32) -> u32 {
|
||||
if x == 1 {
|
||||
return 1;
|
||||
use std::ops::Sub;
|
||||
use std::fmt::Display;
|
||||
use num_traits::identities::One;
|
||||
|
||||
fn fact<T: PartialOrd + PartialEq + One + Sub<Output = T> + Copy + Display>(x: T) -> T {
|
||||
if x < T::one() {
|
||||
panic!("Invalid number: {}", x);
|
||||
}
|
||||
|
||||
return x * fact(x - 1);
|
||||
if x.is_one() {
|
||||
return T::one();
|
||||
}
|
||||
|
||||
return x * fact(x - T::one());
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
Reference in New Issue
Block a user