Problem two steps things up just a smidgen.

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

The challenge of this problem is to accurately calculating the Fibonacci sequence while summing only the even-valued terms. Ruby allows us to treat arrays like stacks, so I can easily push a value onto the stack after calculating it as the next term. Using the **last** method on an array is a neat trick in Ruby to get the value of the last element in an array. I did not need to keep an entire array of Fibonacci values, but chose to since I wanted to print a list of all the values at the end. It was initially for debugging, and then because I was curious as to what last the Fibonacci number before 4 million was. You’ll see again that I wrote my code for the general case for the sum of even Fibonacci values under N with a default of 4,000,000.

[sourcecode language=“ruby”]

#!/usr/bin/env ruby

class Problem

# Create the object

def initialize (n)

@n = n.to_i

end

# Solve it

def solve

puts “Solving for sum of even numbers in fib sequence under 4 million“

fib = [0,1]

sum = 0

while(fib.last < @n)
tmp = fib.last + fib[fib.length — 2]
if tmp % 2 == 0 && tmp < @n
puts “Adding #{tmp} + #{sum} = #{tmp+sum}“
sum += tmp
end
fib.push tmp
end
puts fib.join(“, ”)
puts “Sum: #{sum}“
end
end
if __FILE__ == $0
# Initialize the program
p = Problem.new ARGV[0] || 4000000
p.solve
end
[/sourcecode]