Implement factorial using generic mathematics

This commit is contained in:
Alexander Launi
2020-03-21 17:20:03 -04:00
parent 2ff4f42d43
commit 24c91a4a0b
2 changed files with 13 additions and 4 deletions

View File

@@ -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"

View File

@@ -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() {