use_arithmetic/gcd.rs
1/// Computes the greatest common divisor of two unsigned integers.
2///
3/// This helper uses the Euclidean algorithm and keeps the required edge cases
4/// explicit: `gcd(0, 0) == 0` and `gcd(a, 0) == a`.
5///
6/// # Examples
7///
8/// ```rust
9/// use use_arithmetic::gcd;
10///
11/// assert_eq!(gcd(54, 24), 6);
12/// assert_eq!(gcd(0, 0), 0);
13/// assert_eq!(gcd(21, 0), 21);
14/// ```
15#[must_use]
16pub const fn gcd(mut left: u64, mut right: u64) -> u64 {
17 while right != 0 {
18 let remainder = left % right;
19 left = right;
20 right = remainder;
21 }
22
23 left
24}
25
26#[cfg(test)]
27mod tests {
28 use super::gcd;
29
30 #[test]
31 fn handles_zero_and_positive_cases() {
32 assert_eq!(gcd(0, 0), 0);
33 assert_eq!(gcd(21, 0), 21);
34 assert_eq!(gcd(0, 21), 21);
35 assert_eq!(gcd(54, 24), 6);
36 assert_eq!(gcd(48, 18), 6);
37 }
38}