我想解决欧拉计划的第12道题。这就是问题所在:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
- 1: 1
- 3: 1,3
- 6: 1,2,3,6
- 10: 1,2,5,10
- 15: 1,3,5,15
- 21: 1,3,7,21
- 28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
我定义了两个函数来完成这项工作:
1)allfactor(x)
:这以列表形式给出给定数字的所有因子。例如:allfactor(10)
给我们[1, 2, 5, 10]
2)TriangularNo(x)
:这给了我们第n个三角形数。示例TriangularNo(5)
给出了5
下面是我写的完整代码:
facs=[]
def allfacof(x):
for i in range(1,int(x/2)+1):
if x%i==0:
facs.append(i)
else:
pass
facs.append(x)
return(facs)
def TriangularNo(x):
no=0
for i in range(1,x+1):
no=no+i
return(no)
a=0 # a will tell us the number of iterations
while True:
a+=1
N=TriangularNo(a)
length=(len(allfacof(N)))
if int(length)>=500:
print(N)
break
else:
pass
当我运行这段代码时,我得到了1378
作为输出,这显然是错误的,因为len(allfacof(1378))
结果是8
,而不是问题中要求的500
。你知道吗
注意,在while
循环中,我使用if int(length)>=500:
,这意味着当我的代码运行时,length
以某种方式获得值=500,但当我单独运行函数时,它表示它的长度是8。你知道吗
我就是找不出错误。请帮帮我
问题是您正在使用
facs
作为全局变量,而您只是附加到该项。您应该使它成为allfacof()的成员,以便在每个值之后清除它。 如果你研究facs
,你会发现它等于相关问题 更多 >
编程相关推荐