Euclidean GCD And LCM On Integers

The Euclidean loop replaces the pair with the remainder until it hits zero, and dividing before multiplying keeps the LCM inside u64 bounds.

RustData Integrity

Code

rustsnippet
20 lines
fn gcd(mut a: u64, mut b: u64) -> u64 {
    // Euclidean algorithm: gcd(a, b) = gcd(b, a mod b)
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a
}

fn lcm(a: u64, b: u64) -> u64 {
    // divide before multiplying so the product cannot overflow mid-step
    a / gcd(a, b) * b
}

fn main() {
    println!("gcd(48, 18) = {}", gcd(48, 18));
    println!("gcd(17, 5)  = {}", gcd(17, 5));
    println!("lcm(4, 6)   = {}", lcm(4, 6));
    println!("lcm(21, 6)  = {}", lcm(21, 6));
    println!("gcd(0, 7)   = {}", gcd(0, 7));
}

How the snippet works

Everything happens inside the functions gcd, lcm and main.

The cycling part of this snippet is while b != 0.

What to watch for

  • Self-sufficient by design — there is no registry and no lockfile entry.

Applying it

Entry signature: fn gcd(mut a: u64, mut b: u64) -> u64

The run prints labeled output — gcd(48, 18) =, gcd(17, 5) =, lcm(4, 6) = — when the file runs.

main calls 2 helpers in sequence: gcd and lcm.

Statements that set the outcome here

fn gcd(mut a: u64, mut b: u64) -> u64 {
    // Euclidean algorithm: gcd(a, b) = gcd(b, a mod b)
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a
}
fn lcm(a: u64, b: u64) -> u64 {
    // divide before multiplying so the product cannot overflow mid-step
    a / gcd(a, b) * b
}

Interactive Tools for This Topic

FAQ

What does Euclidean GCD And LCM On Integers print when run?
Invoke the file as-is — the `gcd(48, 18) =`, `gcd(17, 5) =`, `lcm(4, 6) =` prefixes identify which step printed each line.