Difference Of Squares

Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.

The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.

The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.

Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.

You are not expected to discover an efficient solution to this yourself from first principles; research is allowed, indeed, encouraged. Finding the best algorithm for the problem is a key skill in software engineering.

Source

Problem 6 at Project Euler http://projecteuler.net/problem=6

Version compatibility

This exercise has been tested on Julia versions >=1.0.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Your solution


In [ ]:
# submit
"Sum the squares of the numbers up to the given number"
function square_of_sum(n::Int)

end

"Square the sum of the numbers up to the given number"
function sum_of_squares(n::Int)

end

"Subtract sum of squares from square of sums"
function difference(n::Int)

end

Test suite


In [ ]:
using Test

# include("difference-of-squares.jl")

@testset "Square the sum of the numbers up to the given number" begin
    @test square_of_sum(5)::Integer == 225
    @test square_of_sum(10)::Integer == 3025
    @test square_of_sum(100)::Integer == 25502500
end

@testset "Sum the squares of the numbers up to the given number" begin
    @test sum_of_squares(5)::Integer == 55
    @test sum_of_squares(10)::Integer == 385
    @test sum_of_squares(100)::Integer == 338350
end

@testset "Subtract sum of squares from square of sums" begin
    @test difference(0)::Integer == 0
    @test difference(5)::Integer == 170
    @test difference(10)::Integer == 2640
    @test difference(100)::Integer == 25164150
end

Prepare submission

To submit your exercise, you need to save your solution in a file called difference-of-squares.jl before using the CLI. You can either create it manually or use the following functions, which will automatically write every notebook cell that starts with # submit to the file difference-of-squares.jl.


In [ ]:
# using Pkg; Pkg.add("Exercism")
# using Exercism
# Exercism.create_submission("difference-of-squares")