Effectively check if two numbers are relatively prime numbers (relatively prime)?

What is the most efficient ("pythonic") way to check / check if two numbers are mutually prime (relatively prime) in Python.

At 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 verification / testing, if the two numbers are relatively simple, be considered "python" or is there some better way?

+9
source share
1 answer

gcd. , gcd, math ( Python 3.5), .

coprime2, gcd:

from math import gcd as bltin_gcd

def coprime2(a, b):
    return bltin_gcd(a, b) == 1

- , math.gcd C (. math_gcd mathmodule.c):

%timeit coprime(14, 15)
1000000 loops, best of 3: 907 ns per loop

%timeit coprime2(14, 15)
1000000 loops, best of 3: 486 ns per loop

Python <= 3.4 fractions.gcd, , @user2357112, C. , , , .

+12

Source: https://habr.com/ru/post/1655706/


All Articles