题目:
引用
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.
我的python代码:
sum_sq = 0
sq_sum = 0
for i in range(100):
sum_sq += (i + 1) ** 2
sq_sum += (i + 1)
print sq_sum ** 2 - sum_sq
看了别人写的,看来把它化简成公式更简单:
引用
(1 + 2 + ... + n)^2 = n^2 * (n+1)^2 * 1/4
1^2 + 2^2 + ... + n^2 = n * (n+1) * (2n+1) * 1/6
code:
sum_sq = 0
sq_sum = 0
n = 100
sum_sq += n * (n + 1) * (2 * n + 1) / 6
sq_sum += ((n ** 2) * (n + 1) ** 2) / 4
print sq_sum - sum_sq