Skip to content

Commit

Permalink
ch02 up through handling command line arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
francoposa committed Jul 18, 2021
1 parent 9d2b1ac commit b484042
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**/target
**/.idea/*
**/.vscode/*
**/.DS_Store
7 changes: 7 additions & 0 deletions ch02-a-tour-of-rust/gcd/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions ch02-a-tour-of-rust/gcd/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "gcd"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
38 changes: 38 additions & 0 deletions ch02-a-tour-of-rust/gcd/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use std::env;
use std::str::FromStr;

fn main() {
let mut numbers = Vec::new();
for arg in env::args().skip(1) {
numbers.push(u64::from_str(&arg).expect("error parsing integer argument"));
}
if numbers.len() == 0 {
eprintln!("Usage: gcd NUMBER ...");
std::process::exit(1);
}

let mut d = numbers[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}
println!("The greatest common divisor of {:?} is {}", numbers, d);
}

fn gcd(mut m: u64, mut n: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}

#[test]
fn test_gcd() {
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2 * 3 * 5 * 11 * 17, 3 * 7 * 11 * 13 * 19), 3 * 11,);
}

0 comments on commit b484042

Please sign in to comment.