Project Euler: Problem 2

Prob­lem two steps things up just a smidgen.

Each new term in the Fibonacci sequence is gen­er­ated by adding the pre­vi­ous two terms. By start­ing 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 chal­lenge of this prob­lem is to accu­rately cal­cu­lat­ing the Fibonacci sequence while sum­ming only the even-valued terms. Ruby allows us to treat arrays like stacks, so I can eas­ily push a value onto the stack after cal­cu­lat­ing 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 ele­ment in an array. I did not need to keep an entire array of Fibonacci val­ues, but chose to since I wanted to print a list of all the val­ues at the end. It was ini­tially for debug­ging, and then because I was curi­ous as to what last the Fibonacci num­ber before 4 mil­lion was. You’ll see again that I wrote my code for the gen­eral case for the sum of even Fibonacci val­ues under N with a default of 4,000,000.

[source­code language=“ruby”]
#!/usr/bin/env ruby

class Prob­lem

# Cre­ate the object
def ini­tial­ize (n)
@n = n.to_i

# Solve it
def solve
puts “Solv­ing for sum of even num­bers in fib sequence under 4 mil­lion“
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 # Ini­tial­ize the pro­gram p = ARGV[0] || 4000000 p.solve end [/sourcecode]