determine if two numbers are coprime in swift

Two numbers are coprime if their greatest common divisor (GCD) is 1. Here is a Swift function that determines if two numbers are coprime based on calculating their GCD using Euclid's algorithm:

func isCoprime(_ a: Int, _ b: Int) -> Bool {
    var x = a
    var y = b
    while y != 0 {
        let temp = y
        y = x % y
        x = temp
    }
    return x == 1
}
174 chars
11 lines

In this function, we first initialize two variables, x and y, to the values of the input numbers a and b, respectively. We then enter a while loop that calculates the GCD of x and y by repeatedly taking the remainder of x divided by y and swapping x and y until y becomes 0. Finally, we return true if the GCD is 1 (i.e. the numbers are coprime) or false otherwise.

You can call this isCoprime function to determine if two numbers, say m and n, are coprime, like this:

if isCoprime(m, n) {
    print("\(m) and \(n) are coprime.")
} else {
    print("\(m) and \(n) are not coprime.")
}
116 chars
6 lines

related categories

gistlibby LogSnag