【问题标题】:How to enhance the time complexity of finding if N is Coprime with the numbers from 2 till N using Python?如何使用 Python 提高查找 N 是否为 Coprime 的时间复杂度,其中数字从 2 到 N?
【发布时间】:2020-07-23 06:57:34
【问题描述】:

我已经编写了我的代码,它包含 2 个方法 coprime() 来检查 2 个数字是否互质,count_coprime() 来计算与 n 互质的数字,它可以工作,但是太慢了我正在寻找改进:

第一个:

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

第二个:

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

【问题讨论】:

标签: python performance math time-complexity


【解决方案1】:

要检查两个数是否互质,可以使用 GCD (Great Common Divisor) 算法。如果gcd(a,b)==1,那么值是互质的。它在O(max(log(a),log(b))) 时间内工作,因此总体复杂度为O(nlogn)

请注意,标准数学模块已经包含math.gcd() 函数。欧几里得算法的简单实现:

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

【讨论】:

  • 感谢您的回答,但我想知道gcd() 是如何以如此有效的方式实现的?幕后发生了什么?
  • 了解“gcd”术语,您可以轻松找到和阅读成千上万的描述和实现。添加了规范的 Python 实现。
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 2022-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多