我在Project Euler#6中遇到了问题。问题如下:python project euler 6 with any number
找到前100个自然数的平方和与平方和的差值。
我试图写我的代码,以欧拉(所有数字最高可达100)都可以代替你喜欢的任何数字(所有数字都包括x)。我决定为了做到这一点,你需要3个功能。代码是:
#the sumSquare function squares every number from 0 to number called
#in the function and adds each term to a list. the function returns the sum
#of all numbers in this list
def sumSquare(num):
list1 = []
for i in range(num+1):
x = i^2
list1.append(x)
return sum(list1)
#the squareSum function adds every whole number from 0 up to and including
#the number called in the function to list2. It returns the sum squared of #every number in the list
def squareSum(num):
list2 = []
for i in range(1,num+1):
list2.append(i)
return (sum(list2) * sum(list2))
def ans(num):
return squareSum(num) - sumSquare(num)
print ans(100)
我的输出为2549748,但我在网上正确的解决方案是25164150.有谁看到我错读。我只是在学习代码,所以我可能会错过某些更容易被更有经验的人发现的东西。但据我所知,这些清单在总结之前会被填入适当的数字。
Unreleated但范围返回一个列表,所以不需要迭代并将值添加到第二个列表。总和(范围(1,num + 1))'将起作用。 – Alan