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
#![no_std]
pub trait Gcd {
fn gcd(self, other: Self) -> Self;
}
macro_rules! gcd_impl {
($($t:ty),*) => ($(
impl Gcd for $t {
fn gcd(self, other: Self) -> Self {
let (mut a, mut b) = if self > other {
(self, other)
} else {
(other, self)
};
while b != 0 {
let r = a % b;
a = b;
b = r;
}
a
}
}
)*)
}
gcd_impl! { u8, u16, u32, u64, usize }
#[cfg(test)]
mod test {
use super::Gcd;
#[test]
fn test_gcd() {
assert_eq!(0, 0u8.gcd(0));
assert_eq!(10, 10u8.gcd(0));
assert_eq!(10, 0u8.gcd(10));
assert_eq!(10, 10u8.gcd(20));
assert_eq!(44, 2024u32.gcd(748));
}
}