Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

Given a number, find the sum of all the unique multiples of particular numbers up to but not including that number.

If we list all the natural numbers below 20 that are multiples of 3 or 5, we get 3, 5, 6, 9, 10, 12, 15, and 18.

The sum of these multiples is 78.

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.

A variation on Problem 1 at Project Euler http://projecteuler.net/problem=1

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

```
local sum_of_multiples = require('sum-of-multiples')
describe('sum-of-multiples', function()
it('should sum multiples of a single number', function()
assert.same(9, sum_of_multiples({ 3 }).to(7))
assert.same(15, sum_of_multiples({ 5 }).to(12))
end)
it('should sum multiples of a list of numbers', function()
assert.same(33, sum_of_multiples({ 3, 5 }).to(11))
assert.same(129, sum_of_multiples({ 7, 3 }).to(25))
assert.same(153, sum_of_multiples({ 7, 3, 8 }).to(25))
end)
it('should calculate multiples up to, but not including, the limit', function()
assert.same(9, sum_of_multiples({ 3 }).to(9))
assert.same(23, sum_of_multiples({ 3, 5 }).to(10))
end)
it('should not include a multiple more than once', function()
assert.same(35, sum_of_multiples({ 2, 5 }).to(11))
assert.same(sum_of_multiples({ 2 }).to(11), sum_of_multiples({ 2, 4 }).to(11))
end)
end)
```

```
return function(input)
local input = input or { 3, 5 }
local elements = {}
local sum = 0
local function to(end_number)
for _, value in ipairs(input) do
for i = 1, end_number do
if i * value < end_number then elements[i * value] = true
else break end
end
end
for key, _ in pairs(elements) do
sum = sum + key
end
return sum
end
return {to = to}
end
```

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,276 exercises across 51 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments