Skip to content

Instantly share code, notes, and snippets.

@hibri
Created April 6, 2011 13:07
Show Gist options
  • Save hibri/905606 to your computer and use it in GitHub Desktop.
Save hibri/905606 to your computer and use it in GitHub Desktop.
"""
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, ...
By considering the terms in the Fibonacci sequence
whose values do not exceed four million, find the sum
of the even-valued terms.
"""
describe 'sum even-valued Fibonacci sequence terms below 4 million' do
it 'should be 4613732' do
fib = Fib.new
fib.sum_even_sequence.should == 4613732
end
end
class Fib
def sum_even_sequence
result = [1, 2]
sum = 2
i=2
while result.last < 4_000_000
total = result[i-1] + result[i-2]
result << total
sum += total if total.even?
i += 1
end
return sum
end
end
@njpearman
Copy link

Ruby...? I think that this works, too:

def fib first, second, total=0
return total if second > 4000000
second.even? ? fib(second, first + second, total + second) : fib(second, first + second, total)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment