Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

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.

To run the tests, run the command `busted`

from within the exercise directory.

For more detailed information about the Lua track, including how to get help if you're having trouble, please visit the exercism.io Lua language page.

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

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

```
local diff = require('difference-of-squares')
describe('difference-of-squares', function()
describe('square_of_sums', function()
it('should square the sum of the numbers up to the given number', function()
assert.equal(225, diff.square_of_sums(5))
assert.equal(3025, diff.square_of_sums(10))
assert.equal(25502500, diff.square_of_sums(100))
end)
end)
describe('sum_of_squares', function()
it('should sum the squares of the numbers up to the given number', function()
assert.equal(55, diff.sum_of_squares(5))
assert.equal(385, diff.sum_of_squares(10))
assert.equal(338350, diff.sum_of_squares(100))
end)
end)
describe('difference_of_squares', function()
it('should subtract sum of squares from square of sums', function()
assert.equal(0, diff.difference_of_squares(0))
assert.equal(170, diff.difference_of_squares(5))
assert.equal(2640, diff.difference_of_squares(10))
assert.equal(25164150, diff.difference_of_squares(100))
end)
end)
end)
```

```
local degree = 2
local function square_of_sums(n)
local sum = 0
for i = 0, n do
sum = sum + i
end
return math.pow(sum, degree)
end
local function sum_of_squares(n)
local sum = 0
for i = 0, n do
sum = sum + math.pow(i, degree)
end
return sum
end
local function difference_of_squares(n)
return square_of_sums(n) - sum_of_squares(n)
end
return {
square_of_sums = square_of_sums,
sum_of_squares = sum_of_squares,
difference_of_squares = difference_of_squares
}
```

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,394 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments