From 499def9207fc04d6fb66204666cce3b907c69dbb Mon Sep 17 00:00:00 2001 From: Emerentius Date: Fri, 11 Sep 2015 20:33:39 +0200 Subject: [PATCH] Added tests for gcd compare gcd with euclidean gcd test panics on gcd(min_val, min_val) and gcd(min_val, 0) for signed integers --- src/integer.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/integer.rs b/src/integer.rs index 2d39bda..2fcd51f 100644 --- a/src/integer.rs +++ b/src/integer.rs @@ -360,6 +360,47 @@ macro_rules! impl_integer_for_isize { assert_eq!((-6 as $T).gcd(&3), 3 as $T); assert_eq!((-4 as $T).gcd(&-2), 2 as $T); } + #[test] + fn test_gcd_cmp_with_euclidean() { + fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { + while m != 0 { + ::std::mem::swap(&mut m, &mut n); + m %= n; + } + + n.abs() + } + + // gcd(-128, b) = 128 is not representable as positive value + // for i8 + for i in -127..127 { + for j in -127..127 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + } + + // last value + // FIXME: Use inclusive ranges for above loop when implemented + let i = 127; + for j in -127..127 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + assert_eq!(127.gcd(&127), 127); + } + + #[test] + #[should_panic] + fn test_gcd_min_val_min_val() { + let min = <$T>::min_value(); + min.gcd(&min); + } + + #[test] + #[should_panic] + fn test_gcd_min_val_0() { + let min = <$T>::min_value(); + min.gcd(&0); + } #[test] fn test_lcm() { @@ -498,6 +539,31 @@ macro_rules! impl_integer_for_usize { assert_eq!((56 as $T).gcd(&42), 14 as $T); } + #[test] + fn test_gcd_cmp_with_euclidean() { + fn euclidean_gcd(mut m: $T, mut n: $T) -> $T { + while m != 0 { + ::std::mem::swap(&mut m, &mut n); + m %= n; + } + n + } + + for i in 0..255 { + for j in 0..255 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + } + + // last value + // FIXME: Use inclusive ranges for above loop when implemented + let i = 255; + for j in 0..255 { + assert_eq!(euclidean_gcd(i,j), i.gcd(&j)); + } + assert_eq!(255.gcd(&255), 255); + } + #[test] fn test_lcm() { assert_eq!((1 as $T).lcm(&0), 0 as $T);