DEV Community

Discussion on: JavaScript Challenge 7: Multiples of 3 or 5

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

You missed a very obvious optimization there:

(code in Lua because it's what's easiest for me :D)

local function answer(n)
   local acc = 0
   for i=3, n-1, 3 do
      if i % 5 > 0 then
         acc = acc + i
      end
   end
   for i=5, n-1, 5 do
      acc = acc + i
   end
   return acc
end
Enter fullscreen mode Exit fullscreen mode

This will only iterate over numbers you actually need to add and skip the doubles :D

However, there's a more complex approach you can take:

local function sum_from_1_to_n(n)
    n = math.floor(n)
    return n * n / 2 + n/2
end

local function answer(n)
    n = n - 1
    local multiples_of_3 = 3 * sum_from_1_to_n(n / 3)
    local multiples_of_5 = 5 * sum_from_1_to_n(n / 5)
    local common_multiples = 15 * sum_from_1_to_n(n / 15)
    return multiples_of_3 + multiples_of_5 - common_multiples
end
Enter fullscreen mode Exit fullscreen mode

If necessary I can write an article explaining how that one works ;)

Collapse
 
albertomontalesi profile image
AlbertoM

Awesome, yeah since we are calculating numbers in succession from 1 to x we can totally do it this way rather than looping.

Collapse
 
newbie322 profile image
Friday

Is Lua some programming language or something?

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️