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:
174 chars11 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:
116 chars6 lines
gistlibby LogSnag