Chapter 21

Home

Least Common Multiple

The LCM of two numbers is the smallest positive integer that both divide. Thanks to GCD, computing LCM is a one-liner.

LCM from GCD

The relationship is simple:

LCM(a, b) = a / GCD(a, b) * b

Divide first to avoid overflow: (a / gcd) × b stays smaller than a × b / gcd.

C++

int lcm(int a, int b) {
    return a / gcd(a, b) * b;
}

Rust

fn lcm(a: u64, b: u64) -> u64 {
    a / gcd(a, b) * b
}

⚠️ Watch for overflow

For numbers up to 10⁹, a × b can overflow a 32-bit int. Always use long long (C++) or u64 (Rust) for LCM.

Problem: LCM of an Array

Compute LCM across multiple numbers by folding: LCM(a, b, c) = LCM(LCM(a, b), c).

C++

long long result = 1;
for (int x : arr) {
    result = lcm(result, x);
}

Rust

let result = arr.iter().fold(1, |acc, &x| lcm(acc, x));

Key Takeaways

Practice