expression

Greatest common divisor and checked least common multiple

Use Euclid’s algorithm to find a greatest common divisor. Define lcm as zero if either input is zero. Divide first to reduce overflow risk, then check multiplication. Expected stdout (not executed): 6 Some(72) None Common mistake: Multiplying first or dividing by gcd(0,0).

Formal Syntax & Structure

rust syntaxrust
gcd(a,b); (a / gcd(a,b)).checked_mul(b)

Working Example

Example Snippetrust
fn main() {    fn gcd(mut a: u32, mut b: u32) -> u32 {        while b != 0 { (a,b) = (b,a % b); }        a    }    fn lcm(a: u32,b: u32) -> Option<u32> {        if a == 0 || b == 0 { return Some(0); }        (a / gcd(a,b)).checked_mul(b)    }    println!("{} {:?}", gcd(18,24), lcm(18,24));    println!("{:?}", lcm(u32::MAX,2));}
Rust Reference