Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently check if two numbers are co-primes (relatively primes)?

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?

like image 318
Erba Aitbayev Avatar asked Sep 24 '16 17:09

Erba Aitbayev


People also ask

How do you know if 2 numbers are relatively prime?

Two integers are relatively prime (or coprime) if there is no integer greater than one that divides them both (that is, their greatest common divisor is one). For example, 12 and 13 are relatively prime, but 12 and 14 are not.

What is the difference between coprime and relatively prime numbers?

A co-prime number is a pair of numbers with no divisor other than the common one. A set of relatively prime numbers must consist of at least two numbers. The relatively prime number is only one as the greatest common divisor. For example, prime numbers are 4 and 7, 5, 7, and 9.

What is the probability that two numbers are relatively prime?

While the probability of a random number being prime decreases as the range of possible random numbers increases (Prime Number Theorem), the probability of two random numbers being relatively prime is 60.8% Is this something that is either well known by or trivially obvious to prime number gurus?

How do you prove two variables are coprime?

Définition 1.1 Two integers a and b are coprime if gcd(a, b)=1.


1 Answers

The only suggestion for improvement might be with your function gcd. Namely, you could use gcd that's defined in math (for Python 3.5) for a speed boost.

Defining coprime2 that uses the built-in version of gcd:

from math import gcd as bltin_gcd

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

You almost cut down execution speed by half due to the fact that math.gcd is implemented in C (see math_gcd in 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

For Python <= 3.4 you could use fractions.gcd but, as noted in a comment by @user2357112, it is not implemented in C. Actually, there's really no incentive to actually use it, its implementation is exactly the same as yours.

like image 135
Dimitris Fasarakis Hilliard Avatar answered Oct 05 '22 13:10

Dimitris Fasarakis Hilliard