What is the most efficient ("pythonic") way to test/check if two numbers are co-primes (relatively prime) in Python.
For the moment I have this code:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def coprime(a, b):
return gcd(a, b) == 1
print(coprime(14,15)) #Should be true
print(coprime(14,28)) #Should be false
Can the code for checking/testing if two numbers are relatively prime be considered "Pythonic" or there is some better way?
The only suggestion for improvement might be with your function
gcd
. Namely, you could usegcd
that's defined inmath
(for Python3.5
) for a speed boost.Defining
coprime2
that uses the built-in version ofgcd
:You almost cut down execution speed by half due to the fact that
math.gcd
is implemented inC
(seemath_gcd
inmathmodule.c
):For Python
<= 3.4
you could usefractions.gcd
but, as noted in a comment by @user2357112, it is not implemented inC
. Actually, there's really no incentive to actually use it, its implementation is exactly the same as yours.