Skip to main content

nekolib/math/
lcm.rs

1//! 最小公倍数。
2
3use super::gcd;
4
5/// 最小公倍数。
6///
7/// # Complexity
8/// $O(\\log(\\min\\{m, n\\}))$ time.
9///
10/// # Examples
11/// ```
12/// use nekolib::math::Lcm;
13///
14/// assert_eq!(12_u32.lcm(18), 36);
15/// assert_eq!(13_i32.lcm(-3), -39);
16/// assert_eq!(60_u32.lcm(90).lcm(150), 900);
17///
18/// assert_eq!(0_u32.lcm(0), 0);
19/// assert_eq!(0_u32.lcm(1), 0);
20/// ```
21pub trait Lcm {
22    fn lcm(self, other: Self) -> Self;
23}
24
25use gcd::Gcd;
26
27macro_rules! impl_int {
28    ($t:ty) => {
29        impl Lcm for $t {
30            fn lcm(self, other: Self) -> Self {
31                if self == 0 || other == 0 {
32                    0
33                } else {
34                    self / self.gcd(other) * other
35                }
36            }
37        }
38    };
39    ( $($t:ty)* ) => { $(impl_int!($t);)* };
40}
41
42impl_int!(u8 u16 u32 u64 u128 usize);
43impl_int!(i8 i16 i32 i64 i128 isize);