find the greatest common divisor of two numbers in swift

To find the greatest common divisor (GCD) of two numbers in Swift, we can use the Euclidean algorithm.

main.swift
func gcd(_ a: Int, _ b: Int) -> Int {
    let modulo = a % b
    if modulo == 0 {
        return b
    } else {
        return gcd(b, modulo)
    }
}
150 chars
9 lines

Here, we define a recursive function gcd that takes two integers a and b as parameters. We first find the remainder of a divided by b using the modulo operator %. If the remainder is zero, then the GCD is b, and we return it. Otherwise, we recursively call the gcd function with b and the remainder as the new parameters. This continues until we reach a point where the remainder is zero and we can return the GCD.

We can call the gcd function with two numbers like this:

main.swift
let a = 24
let b = 36
let result = gcd(a, b)
print("GCD of \(a) and \(b) is \(result)") // Output: GCD of 24 and 36 is 12
122 chars
5 lines

This will output GCD of 24 and 36 is 12, which is the correct answer.

gistlibby LogSnag