New to StackOverflow here. I’m working on the first Euler problem and have run into an issue where I can get the statement to iterate through the array. It seems like it has something to do with the way I have the while loop setup but I can’t figure it out.
Here’s my code:
#euler problem 1
numbers = [3,5]
sum = 0
i=1
total=0
numbers.each do |number|
while i * number < 10
adder = i * number
total += adder
i += 1
puts total
end
end
puts total
The output is 3
9
18
18
Any idea why it isn’t processing the 5 in the array numbers?
Your problem is that
iis declared outside the block so whennumberis five,iis already four and thewhileloop’s condition fails immediately because20 < 10is false. Try it like this:If you put a little
putsin your code you’ll see what’s going on:That will give you this output:
and you’ll see the problem with
i.