find the least common multiple of a list of numbers in swift

Here's a function in Swift to find the least common multiple of a list of numbers using the Euclidean algorithm:

main.swift
func lcm(numbers: [Int]) -> Int {
    func gcd(_ a: Int, _ b: Int) -> Int {
        return b == 0 ? a : gcd(b, a % b)
    }
    return numbers.reduce(1) { lcm, n in
        lcm * n / gcd(lcm, n)
    }
}
203 chars
9 lines

How it works:

  • The inner function gcd returns the greatest common divisor of two numbers using the Euclidean algorithm.
  • The function lcm takes an array of integers and reduces them to a single value, using the formula lcm(a, b) = a * b / gcd(a, b) to calculate the least common multiple of the accumulated value and each number in the array.

gistlibby LogSnag