You use a constant N
as your variable... not dreadful, but a little confusing.
You first ask the user for how many times they want to run the code, then for which number to sum the mods of 3 & 5 for; it would be simpler to just write the code which asks for a number and works the sum - if the user wants to run it multiple times, then let them! :-)
No need to start at zero - 0,1, & 2 are never going to be divisible by three (although we'd need to add some validation in case the user adds a very low number)
Instead of setting up an intermediate arr
value and iterating with each
, you can select
to get the numbers that return true for the block.
But your main question is about speed - have you benchmarked your code to find out if the speed is an issue?
n = gets.to_i
return 0 unless n > 2 # you could do this as a ternary or `if` statement if you prefer
(3...n).select { |j| j % 3 == 0 || j % 5 == 0 }.reduce(:+)
N
— the number mentioned in your challenge, or the number of times to repeat the challenge? \$\endgroup\$