Problem 2
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.
Solution
#By considering the terms in the Fibonacci sequence
#whose values do not exceed four million, find the
#sum of the even valued terms.
# this uses the same technique
# as the c# implementation
# I find this initialization
# syntax interesting
answer = 0
fib0, fib1, fib2 = 1, 1, 2;
while fib2 < 4000000
answer += fib2
#odd + even = odd
fib0 = fib1 + fib2;
#odd + even = odd
fib1 = fib0 + fib2;
#odd + odd = even
fib2 = fib0 + fib1;
end
puts answer
Discussion
This is obviously a port of the C# solution. The one piece I find interesting is
fib0, fib1, fib2 = 1,1,2;
Seems to be equivalent to
fib0 = 1, fib1 = 1, fib2 = 2;
For cutting and pasting large lists, the first option might be more attractive? Why not use an array in that case? I suppose I’ll learn more as I continue down the path.
If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).
Leave a Reply