Which const implementation of LCM do y'all prefer?

I think I prefer 1 because it seems the easiest to groc, but I really don't like the triple indent.

// 1
const fn lcm(nums: &[u64]) -> u64 {
    match nums {
        [] => 1,
        [a, xs @ ..] => {
            let b = lcm(xs);
            *a * b / gcd(*a, b)
        }
    }
}
// 2
const fn lcm(nums: &[u64]) -> u64 {
    let [a, xs @ ..] = nums else { return 1 };

    let b = lcm(xs);
    *a * b / gcd(*a, b)
}
// 3
const fn lcm(nums: &[u64]) -> u64 {
    if let [a, xs @ ..] = nums {
        let b = lcm(xs);
        *a * b / gcd(*a, b)
    } else {
        1
    }
}
const fn lcm(nums: &[u64]) -> u64 {
    let &[a, ref xs @ ..] = nums else { return 1 };

    let b = lcm(xs);
    a * (b / gcd(a, b))
}

But it's not a big deal in any case, none are atrocious.

I do suggest dividing before multiplying to overflow in less cases.

1 Like