The answer is much faster (constant time):
def sum_multiples(multiple, to) n = (to-1) / multiple n * (n+1) / 2 * multiple end irb(main):001:0> sum_multiples(3, 10) + sum_multiples(5, 10) - sum_multiples(15, 10) => 23 irb(main):002:0> sum_multiples(3, 1000) + sum_multiples(5, 1000) - sum_multiples(15, 1000) => 233168
Why does it work? sum_multiples sum of the multiples of multiple up, but not including to (it relies on integer division). First, it calculates the number of summed sums ( n ), then multiplies the standard formula by the sum 1..n = n (n + 1) / 2 by multiple . Using this, we can sum the sums for multiples of 3 and 5. Then we should not forget that some numbers are multiples of both 3 and 5, so we subtract the multiples of 15 (3 * 5).
Although your answer is more than fast enough for limitations in this problem (it should work for about 1 millisecond on modern equipment), a faster solution, such as the one I provide, will produce results in very large quantities.
marcog
source share