How to calculate the GCD (greatest common divisor) of two numbers in Rust

1 Answer

0 votes
fn gcd(a: i32, b: i32) -> i32 {
    let mut gcd = 0;
    let mut i = if a < b { a } else { b };

    while i > 0 {
        if a % i == 0 && b % i == 0 {
            gcd = i;
            break;
        }
        i -= 1;
    }

    gcd
}

fn main() {
    let a = 12;
    let b = 20;
    
    println!("The GCD (greatest common divisor) of {} and {} is: {}", a, b, gcd(a, b));
}



  
/*
run:

he GCD (greatest common divisor) of 12 and 20 is: 4

*/

 



answered Apr 27, 2023 by avibootz
edited Sep 4, 2024 by avibootz
...