gcd using args

This commit is contained in:
Sangeeth Sudheer 2022-08-16 01:23:54 +05:30
parent 1f75203146
commit 7a6db2e0fc

View File

@ -1,3 +1,8 @@
// The below imported trait/extension is for adding a `from_str` method which will let us convert
// strings to other types
use std::env;
use std::str::FromStr;
fn gcd(mut a: u64, mut b: u64) -> u64 {
while a > 0 {
if a < b {
@ -18,8 +23,22 @@ fn test_gcd() {
}
fn main() {
println!("gcd(4, 6) is {}", gcd(4, 6));
println!("gcd(7, 49) is {}", gcd(7, 49));
println!("gcd(3, 7) is {}", gcd(3, 7));
println!("gcd(128, 16) is {}", gcd(128, 16));
let mut numbers = Vec::new();
for arg in env::args().skip(1) {
numbers.push(u64::from_str(&arg).expect("error parsing argument"));
}
if numbers.len() == 0 {
eprintln!("Usage: gcd NUMBER ...");
std::process::exit(1);
}
let mut result = numbers[0];
for num in &numbers[1..] {
result = gcd(*num, result);
}
println!("The greatest common divisor of {:?} is {}", numbers, result);
}