[英]Why does it take forever to run my python code even for a small input?
我是编程新手,也是这个网站的新手。 非常抱歉,如果我的代码很愚蠢,我正在浪费您的时间。 我一直在尝试解决欧拉计划问题12 。 在互联网的一点帮助下,我想出了一种算法,并用python编写了代码。 我尝试对其进行概括,以使其不仅适用于所有数字,而且适用于所有数字。500起初,我在获取正确的输出时遇到了问题,但是当我认为我将其修复时,情况变得更糟了,因为该程序要花很长时间才能运行。 您能指出我犯的错误吗?
L = int(input("L="))
def number_of_divisors(n):
global divisors
global count
global p
divisors = 1
count = 0
if n%2 == 0:
while n%2 == 0:
count += 1
n=n/2
divisors = divisors * count
count = 0
p = 3
while n != 1:
while n%p == 0:
count +=1
n = n/p
p += 2
divisors *= (count + 1)
return divisors
def the_first_triangular_number_with_more_than_L_divisors(L):
global total_divisors
global n
total_divisors , n = 1 , 1
while total_divisors <= L:
s = number_of_divisors(n+1)
total_divisors *= s
total_divisors = s
n += 1
return (n*(n+1))/2
x = the_first_triangular_number_with_more_than_L_divisors(L)
print(x)
这可能是一个无限循环。 如果它进入循环并且s <= L,则由于最后一行(可能是拼写错误),它将无限期重复。
while total_divisors <= L:
s = number_of_divisors(n+1)
total_divisors *= s
total_divisors = s
这是一个非常接近您的答案,如果您完全陷入困境,可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.