~janbaudisch/euler-rs

9e1a7f62fe6901cc0e1405dd088ea5435f6a98e4 — Jan Baudisch 5 years ago d2ad5e0
common: add factorial
2 files changed, 33 insertions(+), 0 deletions(-)

A common/src/math/factorial.rs
M common/src/math/mod.rs
A common/src/math/factorial.rs => common/src/math/factorial.rs +31 -0
@@ 0,0 1,31 @@
pub trait Factorial {
    fn factorial(self) -> u64;
}

macro_rules! impl_factorial {
    ($type: ident) => {
        impl Factorial for $type {
            fn factorial(self) -> u64 {
                let mut result: u64 = 1;

                match self {
                    0 | 1 => return 1,
                    2 => return 2,
                    _ => {
                        for n in 2..(self + 1) as u64 {
                            result *= n;
                        }
                    }
                }

                return result;
            }
        }
    };
}

impl_factorial!(u8);
impl_factorial!(u16);
impl_factorial!(u32);
impl_factorial!(u64);
impl_factorial!(u128);

M common/src/math/mod.rs => common/src/math/mod.rs +2 -0
@@ 1,5 1,7 @@
mod factorial;
mod fibonacci;
mod prime;

pub use factorial::*;
pub use fibonacci::*;
pub use prime::*;