Aller au contenu

5#

26/06/22

On continue avec le projet Euler. Le probleme 6 est a propos de sommes et de carres :

Ennoncé

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

\[ 1^2 + 2^2 + 3^2 + \ldots + 10^2 = 385 \]

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

\[ (1 + 2 + 3 + \ldots + 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.

Nous allons essayer dans un premier temps de generaliser le probleme, puis nous verrons la solution programmative.

Generalisation#

On cherche alors :

\[ (1 + 2 + 3 + \ldots + 100)^2 - ( 1^2 + 2^2 + 3^2 + \ldots + 100^2) \]

Ou encore :

\[ (\sum_{i = 1}^{100} i)^2 - (\sum_{j = 1}^{100} j^2) \]

Solution#

Voici le code permettant de resoudre ce probleme assez basique :

"""La somme des carres
"""
def sum_squares(n):
    return sum([pow(x, 2) for x in range(n + 1)])


"""Le carre de la somme
"""
def square_sums(n):
    return pow(sum([x for x in range(n + 1)]), 2)

n = 100
a = sum_squares(n)
b = square_sums(n)

print(a, b, b - a)

# 338350 25502500 25164150