P6
projecteuler.net

Sum Square Difference

ℹ️Published on Friday, 14th December 2001, 06:00 pm; Solved by 525839;
Difficulty rating: 5%

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.



Soluzione

Usando del codice:

sum_of_squares_100_nums = sum([i^2 for i in 1:100])
square_of_sum_100_nums = sum([i for i in 1:100])^2
println(Int64(square_of_sum_100_nums-sum_of_squares_100_nums))
25164150

Mentre affidandoci alle formule matematiche più o meno note

\[ \text{(sum of squares 1 to n)} = \sum_{i=1}^n i^2 = \dfrac{n(n+1)(2n+1)}{6} \] \[ \text{(sum 1 to n)} = \sum_{i=1}^n i = \dfrac{n(n+1)}{2} \]

si ricava comunque la risposta:

f(n) = (n*(n+1)/2)^2 - n*(n+1)*(2n+1)/6
Int64(f(100))
25164150

Last modified: September 20, 2025. Website built with Franklin.jl and the lovely Julia programming language.