# 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. def fib(n) return n if (0..1).include? n fib(n-1) + fib(n-2) end # i is an iterator, start at 2 because the problem says to start with 1 & 2 fibs = Array.new i = 2 f = 0 while f < 4000000 f = fib(i) if f%2==0 fibs << f end i = i + 1 end #sum up the numbers in the array, then output the sum ret = fibs.inject(0) {|x,n| x+n} print "#{ret} is the sum \n" #another way ret2 = 0 f2 = 0 i2 = 2 while f2 < 4000000 f2 = fib(i2) if f2%2==0 ret2 = ret2 + f2 end i2 = i2 + 1 end print "#{ret2} is the sum\n"