Project Euler Problem 006

# Statement

The sum of the squares of the first ten natural numbers is,

1^(2) + 2^(2) + … + 10^(2) = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)^(2) = 55^(2) = 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.

# Solution

For this solution I applied the well known formulas which have constant time:

(1)\begin{align} \sum_{i=1}^N i = \frac {(n * (n+1))} {2} \end{align}

(2)
\begin{align} \sum_{i=1}^N i^2 = \frac {n * (n+1) * (2n+1)} {6} \end{align}

The resulting code:

if __name__ == '__main__': n = 100 result = (((n * (n + 1)) // 2) ** 2) - ((n * (n + 1) * ((2 * n) + 1)) // 6) print("The result is:", result)

The Python file is available for download here.