'''
<span style="color:#ff0000;">注:不再标明题目出处</span>
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.
第一百个,和的平方与平方和的差值
'''
分析:
直接求:和的平方 - 平方的和
def sum_minus_power(target):
<span style="white-space:pre"> </span>return sum([x for x in xrange(target + 1)])**2 - sum([x**2 for x in xrange(target + 1)])
对于实现,还可以这样:
print sum(xrange(target + 1))**2 - sum([n**2 for n in xrange(target + 1)])
直接用xrange()生成的列表进行求和计算
对于后面平方的和,可以采用lambda函数进行改写:
print sum(xrange(target + 1))**2 - sum(map(lambda x: x**2, xrange(target + 1)))
1 + 2 + ... + n = (n + 1) * n / 2
1^2 + 2^2 + ... + n^2 = n * (n + 1) * (2n + 1) / 6
所以,根据这个计算公式,得到:
def sum_minus_power(n):
return ((n + 1) * n / 2) ** 2 - n * (n + 1) * (2 * n + 1) / 6
公式如何证明,可以搜索一下。
因为这里是计算和的平方与平方和的差值,
所以也可以单独实现平方的和与和的平方,
然后返回两个函数计算的差值的结果