'The sum of all numbers less than 1000, multiples of 3 or 5

If we list all natural numbers less than 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all numbers less than 1000, multiples of 3 or 5.

I just started learning Ruby, I used to work only with C languages. Please explain why this code doesn't work. Thank you!!! Code:

sum = 0;
i = 3;
while (i < 1000) do
  if ((i % 3 == 0) || (i % 5 == 0))
    sum += i;
  end
end
puts "The sum of all the multiples of 3 or 5 below 1000: #{sum}"

And when I run the file, it loads indefinitely. enter image description here



Solution 1:[1]

You are never incrementing i.
The while loop will terminate if: i >= 1000
But i = 3 and there is no i+=1 so this loop will never terminate.

Solution 2:[2]

@Raavgo has explained the problem with your code. If you are looking for a fast solution I suggest the following.

 def tot(n, limit)
  m, rem = limit.divmod(n)
  m * (n + limit - rem)/2
 end
tot(3, 999) + tot(5, 999) - tot(15, 999)
  #=> 233168

The term tot(15, 999) is to compensate for double-counting of terms that are divisible by both 3 and 5.

See Numeric#divmod.

Suppose

n = 5
limit = 999

Then

m, rem = limit.divmod(n)
  #=> [199, 4]

So

m   #=> 199
rem #=> 4
  

Then we want to compute

5 + 10 + ... + 999 - rem
  #=> 5 + 10 + ... + 995

This is simply the the sum of an arithmetic progression:

199 * (5 + 995)/2

which equals

m * (n + limit - rem)/2

Solution 3:[3]

(0..1000).select(&->(i){ (i % 3).zero? || (i % 5).zero? }).sum

Solution 4:[4]

(0..1000).filter { |i| i % 3 == 0 || i % 5 == 0 }.sum

your approach is fine if you increment i as said in the other answer, but a more idiomatic Ruby looks like this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raavgo
Solution 2
Solution 3
Solution 4 Joel Blum