'''
Created on 2014年8月29日
Sum square difference
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
@author: wxp2971
'''
# 暴力的方式直接求和计算数值
sumsqr = 0
num = 100
for i in range(1,num+1):
sumsqr += i*i
sqrsum = 0
for i in range(1,num+1):
sqrsum += i
sqrsum *= sqrsum
diff = sqrsum - sumsqr
print(diff)
# 列举出几项观察后,做差只剩下交叉项×2,直接对交叉项累加求和
diff = 0
num = 100
for i in range(1,num+1):
for j in range(i+1,num+1):
diff += 2*i*j
print(diff)
# 利用数列的通项公式计算
num = 100
sum = (num + 1)*num/2
sumsqr = (2*num + 1)*(num + 1)*num/6
diff = sum*sum - sumsqr
print(int(diff))
Project Euler 6
最新推荐文章于 2019-08-08 22:43:22 发布