summaryrefslogtreecommitdiff
path: root/gcd.rs
blob: 0925368d0cac6f83fcdd42f2169c496dbb35a577 (plain)
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
// Synopsis:
//
// $ rustc gcd.rs -o gcd-rs
// $ ./gcd-rs 11 22 33 121
// 11
//

use std::{cmp, env, ops};

fn gcd2<T>(mut a: T, mut b: T) -> T
where
    T: cmp::PartialEq + Copy + ops::Rem<Output = T> + ops::Neg<Output = T>,
{
    while b != -b {
        let c = b;
        b = a % b;
        a = c;
    }

    a
}

fn gcdn<T>(nums: impl IntoIterator<Item = T>) -> Option<T>
where
    T: cmp::PartialEq + Copy + ops::Rem<Output = T> + ops::Neg<Output = T>,
{
    nums.into_iter().reduce(gcd2)
}

fn main() {
    let nums = env::args().skip(1).map(|s| s.parse::<i64>().unwrap());

    if let Some(gcd) = gcdn(nums) {
        println!("{gcd}");
    }
}