How to enhance the time complexity of finding if N is Coprime with the numbers from 2 till N using Python?

Question:

I have wrote my code, it consists of 2 methods coprime() to check if 2 numbers are coprime or not and count_coprime() to count the numbers which are comprime with n and it works, yet it is too slow and I am looking for improvements:

1st:

def coprime(a, b):
    # Returns a boolean value
    # Returns true if a and b are in fact coprime
    if a == 1 or b == 1:
        return True
    else:
        count = 0
        if a < b:
            for i in range(2, a + 1):
                if a % i == 0:
                    if b % i == 0:
                        count += 1
        else:
            for i in range(2, b + 1):
                if b % i == 0:
                    if a % i == 0:
                        count += 1
        return count < 1

2nd:

def count_coprimes(n):
    count = 1
    for i in range(2, n):
        if coprime(i, n):
            count += 1
    return count
Asked By: Sam AlGhamian

||

Answers:

To check whether two numbers are coprime, you can use GCD (Great Common Divisor) algorithm. If gcd(a,b)==1, then values are coprime. It works in O(max(log(a),log(b))) time, so overall compexity is O(logn).

There are some proofs for this here.

Note that standard math module already contains math.gcd() function. Simple implementation of Euclid’s algorithm:

def EuclideanGCD(x, y): 
    while y: 
        x, y = y, x % y 
    return x 
Answered By: MBo