1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
use num_traits::{PrimInt, Signed, Unsigned}; pub trait Gcd: PrimInt + Signed { fn gcd(self, other: Self) -> Self { if other == Self::zero() { self.abs() } else { other.gcd(self % other) } } } pub trait GcdUnsigned: PrimInt + Unsigned { fn gcd(self, other: Self) -> Self { if other == Self::zero() { self } else { other.gcd(self % other) } } } impl<I: Signed + PrimInt> Gcd for I {} impl<I: Unsigned + PrimInt> GcdUnsigned for I {} #[cfg(test)] mod tests { use super::*; #[test] fn test_gcd() { assert_eq!(12i32.gcd(18), 6); assert_eq!((-12i32).gcd(18), 6); assert_eq!(12i32.gcd(-18), 6); assert_eq!((-12i32).gcd(-18), 6); assert_eq!((5i32).gcd(0), 5); assert_eq!((0i32).gcd(5), 5); assert_eq!((-5i32).gcd(0), 5); assert_eq!((0i32).gcd(-5), 5); assert_eq!((0i32).gcd(0), 0); assert_eq!(12u32.gcd(18), 6); assert_eq!(12u128.gcd(18), 6); assert_eq!(12i128.gcd(18), 6); } }