Exercise 1 gcd
simple gcd
cargo new gcd_1
cd gcd_1/src
# edit main.rst
fn gcd(mut m: u64, mut n: u64) -> u64 {
assert!(m != 0 && n != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}
fn main() {
println!("gcd(6, 2) is {}", gcd(6, 2));
}
#[test]
fn test_gcd() {
assert_eq!(gcd(2, 6), 2);
assert_eq!(gcd(3, 5), 1);
}
cargo run prints:
Compiling gcd_1 v0.1.0 (/Users/fangjun/open-source/notes/docs/source/rust/code/gcd_1)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s
Running `target/debug/gcd_1`
gcd(6, 2) is 2
cargo test prints:
Compiling gcd_1 v0.1.0 (/Users/fangjun/open-source/notes/docs/source/rust/code/gcd_1)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.08s
Running unittests src/main.rs (target/debug/deps/gcd_1-74f037a3d4552c7d)
running 1 test
test test_gcd ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
gcd from command line
cargo new gcd_2
cd gcd_2
cd gcd_2/src
# edit main.rs
use std::env;
fn gcd(mut m: u64, mut n: u64) -> u64 {
assert!(m != 0 && n != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("Usage: {} <int1> <int2>", args[0]);
std::process::exit(1);
}
// args[0] is the program name
let num1: u64 = args[1]
.parse()
.expect("Please provide a valid integer for the first argument");
let num2: u64 = args[2]
.parse()
.expect("Please provide a valid integer for the second argument");
let n = gcd(num1, num2);
println!("GCD of {} and {} is {}", num1, num2, n);
}
cargo run 5 15 prints:
Compiling gcd_2 v0.1.0 (/Users/fangjun/open-source/notes/docs/source/rust/code/gcd_2)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
Running `target/debug/gcd_2 5 15`
GCD of 5 and 15 is 5