Implement factorial using generic mathematics
This commit is contained in:
@@ -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