From 4a490014db1ebcefe76ed7c59b17751cebeb83d8 Mon Sep 17 00:00:00 2001 From: Igor Pashev Date: Mon, 28 Nov 2022 18:30:27 +0200 Subject: Update Rust :) --- gcd.rs | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/gcd.rs b/gcd.rs index 95cc865..0925368 100644 --- a/gcd.rs +++ b/gcd.rs @@ -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(mut a: T, mut b: T) -> T +where + T: cmp::PartialEq + Copy + ops::Rem + ops::Neg, +{ + 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(nums: impl IntoIterator) -> Option +where + T: cmp::PartialEq + Copy + ops::Rem + ops::Neg, +{ + nums.into_iter().reduce(gcd2) +} - let gcd = nums.fold(0, gcd2); +fn main() { + let nums = env::args().skip(1).map(|s| s.parse::().unwrap()); - println!("{}", gcd); + if let Some(gcd) = gcdn(nums) { + println!("{gcd}"); + } } -- cgit v1.2.3