Project Euler

Author

Angel Alcala Ruiz

Published

November 20, 2023

Problem 6: Sum Square Difference

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

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

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

\[ \left( 1 + 2 + \ldots + 10 \right)^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 square of the first one hundred natural numbers and the square of the sum.

Let’s solve using Julia

Code
function SumSquareDifference(n)

#' @@name SumSquareDifference
#'
#' @@description
#'
#' This function finds the differnce between the sum of the square of the first n natural numbers and the square of the sum
#'
#' @@arg n: A positive integer n
#'
#' @@return The differnce between the sum of the square of the first n natural numbers and the square of the sum
#'
#' @@examples
#'
#' n = 10
#' SumOfSquareDifference(n)

sum_of_squares = 0
sum = 0

    for i = 1:n
        sum_of_squares = sum_of_squares + (i^2)
        sum = sum + i
    end
    
    square_of_sum = sum^2
    difference = square_of_sum - sum_of_squares
    return difference, square_of_sum, sum_of_squares
end
SumSquareDifference (generic function with 1 method)

Let’s begin by checking the given example of the first 10 natural numbers

Code
SumSquareDifference(10)
(2640, 3025, 385)

Therefore we can see that the difference is 2640 which is the correct solution.

Now let’s find the difference of the sum of the squares of the first one hundred natural numbers and the square of the sum

Code
SumSquareDifference(100)
(25164150, 25502500, 338350)

Therefore the difference is 25,164,150.