Project Euler: #2

Here’s another Project Euler problemhttp://projecteuler.net/index.php?section=pro….

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.

Here was my first go. I was frustrated for a little while because I didn’t realise it was working right up to the point where it gives the final answer, but I hadn’t assigned it to sum. Scratched my head for a while and then assigned sum = 0 which finished up the calculation nicely.

def fibonacci( m, n, finish )
  unless (a = m + n) > finish
    sum = (a % 2 == 0 ? a : 0) + fibonacci( n, a, finish )
    sum = 0

answer = fibonacci 0, 1, 4_000_000
puts "answer: #{answer}"

I was convinced I could get it down to one line. I considered using a fold, but settled for this instead:

def fib( m, n, finish )
  (a = m + n) > finish ? 0 : (a % 2 == 0 ? a : 0) + fib( n, a, finish )

answer = fib 0, 1, 4_000_000
puts "answer: #{answer}"

I’m not sure if the method declaration lines count, so it’s either 1 or 3 (1 if I’m in need of a cuddle.)

Interestingly, someone on the site pointed out that there is an interval of three between each even number (because it’s the sum of the previous two and they’re both odd, summing odds always produces evens). I’m amazed at some people’s powers of observation, I completely missed that. He came up with a pretty quick algorithm because of that. I’ll let you come up with that on your own :p

Added on:
Last updated:
Info:- Ruby version 1.9.2