Overview

 

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, ...\]

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

click for answer

4613732

Solutions

 

Ruby

#!/usr/bin/env ruby
valOne = sum = result = 0
valTwo = 1
until sum > 4000000
   sum = valOne + valTwo
   valOne = valTwo
   valTwo = sum
   if (sum % 2) == 0
      result = sum + result
   end
end
puts result
$ time ruby fibonacci.rb
real	0m0.023s
user	0m0.019s
sys	0m0.003s