Fab Fab - 2 years ago 113
Ruby Question

Sum of even Fibonacci numbers?

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

a = [1,2]
upto = 4_000_000

while a[-2] + a[-1] < upto
a << a[-2] + a[-1]

sum = 0
a.each { |x| sum += x if x.even? }

puts "The result is #{sum}"

How does this work? What is
? What does that even mean? The negative second index of a or a minus 2? Thanks for the explanation.

Answer Source

This is negative index. a[-1] and a[-2] are the last two elements of the array a.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download