我正在尝试解决以下问题:https://projecteuler.net/problem=69。在练习中给出的示例中,它可以很好地工作,但是当我尝试计算n <= 1.000.000的最大值时会崩溃,而当我尝试为n <= 5.000的最大值进行计算时,它已经相当慢了。如何优化我的代码?我正在使用PyScripter。
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def coprime(b):
x = 0 # define a counter for the number of co-primes of b
for a in range(1, b):
if gcd(a, b) == 1: # check if a and b are co-prime
x += 1
return x
def main():
maximum = 1
for n in range(1, 1000001):
m = coprime(n)
x = n / m # calculate n/phi(n)
if x > maximum: # check if you have a new maximum
maximum = n
print(maximum)
if __name__ == '__main__':
main()