Project Euler: Problem 6

https://projecteuler.net/problem=6

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 = 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.


In [1]:
def fn(r):
    s=sum([x**2 for x in range(r+1)]) #sums the square of the first r natural numbers (r+1 in order to be inclusive)
    s2=sum([x for x in range(r+1)]) #sums firt r natural numbers
    difference=s2**2-s # squares the sum and subtracts the sum of the squares
    return difference

In [2]:
print (fn(100))


25164150

In [4]:
# This cell will be used for grading, leave it at the end of the notebook.