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
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
If necessary I can write an article explaining how that one works ;)
Awesome, yeah since we are calculating numbers in succession from 1 to x we can totally do it this way rather than looping.
Is Lua some programming language or something?
Indeed
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You missed a very obvious optimization there:
(code in Lua because it's what's easiest for me :D)
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:
If necessary I can write an article explaining how that one works ;)
Awesome, yeah since we are calculating numbers in succession from 1 to x we can totally do it this way rather than looping.
Is Lua some programming language or something?
Indeed