python - 如何使用 Python 提高从 2 到 N 的数字查找 N 是否为 Coprime 的时间复杂度?
问题描述
我已经编写了我的代码,它包含 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
解决方案
要检查两个数是否互质,可以使用 GCD(Great Common Diviso r)算法。如果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
推荐阅读
- python - Pytesseract OCR 错误文本识别
- r - 如何使用 R 在大型数据帧中加速 forloop grep
- python - Pygame - 从图像的 x 和 y 坐标进行 blitting
- php - dyld:Apple M1 上 php oic8 的惰性符号绑定失败
- php - 为什么这些简单的 Laravel 查询这么慢?
- kotlin - 在 kotlin 中使用 getter 和 setter 时出错
- python-3.x - 对于这个特定示例,如何在 python 中进行字符串格式化
- tensorflow - 超过 grpc 截止日期的部署 tf-serving 问题
- python - 如何编写 python 脚本以在 Window 中运行现有的任务调度程序
- javascript - Lambda@Edge 在源请求上设置 Cookie