Project Euler Problem 6
The sum of the squares of the first ten natural numbers is, The square of the sum of the first ten natural numbers is, H
Solution
We use the identities
$$1+2+\cdots+n=\frac{n(n+1)}{2}$$
and
$$1^2+2^2+\cdots+n^2=\frac{n(n+1)(2n+1)}{6}.$$
For $n=100$:
$$\left(\sum_{k=1}^{100} k\right)^2 = \left(\frac{100\cdot101}{2}\right)^2 = 5050^2 = 25{,}502{,}500.$$
And
$$\sum_{k=1}^{100} k^2 = \frac{100\cdot101\cdot201}{6} = 338{,}350.$$
Therefore the required difference is
$$25{,}502{,}500 - 338{,}350 = 25{,}164{,}150.$$
Python code:
n = 100
sum_of_squares = sum(i*i for i in range(1, n+1))
square_of_sum = sum(range(1, n+1))**2
answer = square_of_sum - sum_of_squares
print(answer)
Tracing the computation:
sum(range(1, 101)) = 50505050**2 = 25502500sum(i*i for i in range(1, 101)) = 338350- Difference $= 25502500 - 338350 = 25164150$
Answer: 25164150