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
CodePudding user response:
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.
CodePudding user response:
(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.
CodePudding user response:
(0..10000).select(&->(i){ (i % 3).zero? || (i % 5).zero? }).sum
CodePudding user response:
@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 algorithmic progression:
m * (5 995)/2
which equals
m * (n limit - rem)/2