diff options
author | Igor Pashev <pashev.igor@gmail.com> | 2022-11-28 18:30:27 +0200 |
---|---|---|
committer | Igor Pashev <pashev.igor@gmail.com> | 2022-11-28 18:30:27 +0200 |
commit | 4a490014db1ebcefe76ed7c59b17751cebeb83d8 (patch) | |
tree | 9f0335dcb6dc2ca6b1ecfd5ce0691f95a6db2547 | |
parent | 10ae1088fe818eb9cb93f566d5e38a9f1c2fd77e (diff) | |
download | gcd-4a490014db1ebcefe76ed7c59b17751cebeb83d8.tar.gz |
Update Rust :)
-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}"); + } } |