我在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