Avatar of JaeHyoLee

JaeHyoLee's solution

to Sum Of Multiples in the Lua Track

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.

Running the tests

To run the tests, run the command busted from within the exercise directory.

Further information

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.

Source

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

Submitting Incomplete Solutions

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

sum-of-multiples_spec.lua

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

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

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?