Friday, January 30, 2009

Project Euler - Problem 2

Alright, on to problem 2. "Find the sum of all the even-valued terms in the [Fibonacci] sequence which do not exceed four million." This one is pretty easy. Just loop through all the numbers in the Fibonacci sequence up to four million. The largest actual number in the sequence that does not exceed 4 million is 3,524,578. Here's is my humble attempt at a solution:

x1,x2 = 0, 1
ans = 0

# While x1 is less than or equal to 4 million
while(x1 <= 4000000)

# Find the next number in the Fibonacci sequence
x1,x2= x2,x1

# If that number is even, then add it to the running sum.
if(x1%2 == 0) then ans += x1 end

puts ans

No comments: