Fab - 2 years ago 113

Ruby Question

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]

end

sum = 0

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

puts "The result is #{sum}"

How does this work? What is

`a[-2]`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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**