find the least common multiple of two numbers in swift

To find the least common multiple of two numbers in Swift, we can use the following algorithm:

  1. Find the greater number between the two input numbers and assign it to a variable called max.
  2. Create a variable called lcm and assign it the value of max.
  3. Create a while loop that will execute as long as both input numbers are not divisible by lcm.
  4. Inside the loop, increment lcm by the value of max.
  5. Return the value of lcm.

Here's the Swift code that implements this algorithm:

main.swift
func leastCommonMultiple(_ a: Int, _ b: Int) -> Int {
    let max = a > b ? a : b
    var lcm = max
    
    while lcm % a != 0 || lcm % b != 0 {
        lcm += max
    }
    
    return lcm
}
193 chars
11 lines

To use this function, simply call it and pass in the two numbers whose least common multiple you want to find:

main.swift
let a = 12
let b = 18

let result = leastCommonMultiple(a, b)

print(result) // Output: 36
91 chars
7 lines

In this example, the least common multiple of 12 and 18 is 36.

gistlibby LogSnag