Skip to content

Instantly share code, notes, and snippets.

@beezly
Last active February 26, 2024 15:51
Show Gist options
  • Save beezly/d7a25f02c7021857d4a8716c790be060 to your computer and use it in GitHub Desktop.
Save beezly/d7a25f02c7021857d4a8716c790be060 to your computer and use it in GitHub Desktop.
Demo rust code for calculating Greatest Common Denominators using Euclidian Algorithm
use std::time::Instant;
const ITERATIONS: i32 = 100000000;
fn main() {
let mut line = String::new();
println!("Input your numbers: ");
let _ = std::io::stdin().read_line(&mut line).unwrap();
let mut split = line.split_whitespace();
let a = split.next().unwrap().parse().unwrap();
let b = split.next().unwrap().parse().unwrap();
let mut result: i32 = 0;
let mut rounds: i32 = 0;
let start_time = Instant::now();
for _ in 0..ITERATIONS {
(result, rounds) = gcd_mut(a,b);
}
let finish_time = Instant::now();
println!("Mutable T GCD: {} Rounds: {}, Duration: {:?} for {} iterations",result,rounds,finish_time.duration_since(start_time),ITERATIONS);
let start_time = Instant::now();
for _ in 0..ITERATIONS {
(result, rounds) = gcd_immut(a,b);
}
let finish_time = Instant::now();
println!("Immutable T GCD: {} Rounds: {}, Duration: {:?} for {} iterations",result,rounds,finish_time.duration_since(start_time),ITERATIONS);
}
fn gcd_mut(mut a: i32, mut b: i32) -> (i32, i32) {
let mut rounds = 0;
let mut t: i32 = 0;
while b != 0 {
t = b;
b = a % b;
a = t;
rounds += 1;
}
(a,rounds)
}
fn gcd_immut(mut a: i32, mut b: i32) -> (i32, i32) {
let mut rounds = 0;
while b != 0 {
let t = b;
b = a % b;
a = t;
rounds += 1;
}
(a,rounds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment