diff options
-rw-r--r-- | gcd.rs | 32 |
1 files changed, 24 insertions, 8 deletions
@@ -1,7 +1,17 @@ -use std::env; +// Synopsis: +// +// $ rustc gcd.rs -o gcd-rs +// $ ./gcd-rs 11 22 33 121 +// 11 +// -fn gcd2(mut a: u64, mut b: u64) -> u64 { - while b != 0 { +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; @@ -10,11 +20,17 @@ fn gcd2(mut a: u64, mut b: u64) -> u64 { a } -fn main() { - // XXX skip(1) to skip program name: - let nums = env::args().skip(1).map(|s| s.parse().unwrap()); +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) +} - let gcd = nums.fold(0, gcd2); +fn main() { + let nums = env::args().skip(1).map(|s| s.parse::<i64>().unwrap()); - println!("{}", gcd); + if let Some(gcd) = gcdn(nums) { + println!("{gcd}"); + } } |