algorithms_edu/algo/math/
factorial.rs

1use num_traits::{PrimInt, Unsigned};
2
3pub trait Factorial: PrimInt + Unsigned {
4    fn factorial(self) -> Self;
5}
6
7macro_rules! impl_factorial {
8    ($T:ty) => {
9        impl Factorial for $T {
10            fn factorial(self) -> Self {
11                match self {
12                    0 => 1,
13                    1 => 1,
14                    _ => self * (self - 1).factorial(),
15                }
16            }
17        }
18    };
19}
20
21impl_factorial!(u8);
22impl_factorial!(u16);
23impl_factorial!(u32);
24impl_factorial!(u64);
25impl_factorial!(u128);
26impl_factorial!(usize);
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    #[test]
32    fn test_factorial() {
33        assert_eq!(0u32.factorial(), 1);
34        assert_eq!(1u32.factorial(), 1);
35        assert_eq!(2u32.factorial(), 2);
36        assert_eq!(3u32.factorial(), 6);
37        assert_eq!(4u32.factorial(), 24);
38    }
39}