【发布时间】: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
【问题讨论】:
-
感谢您的评论,但我想知道
gcd()是如何以如此有效的方式实现的?幕后发生了什么?
标签: python performance math time-complexity