sofiamaMar 25
making it simple. yey!
Q: Problem — Even Fibonacci
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.
code 1 — using i’s and j’s
def even_fibonacci_sum(limit)
i = 1 j = 2
arr = [i , j]
while j < limit
sum = i + j
if sum < limit
arr << sum
end
i = j
j = sum
end
sum = 0
arr.each do |i|
if i % 2 == 0
sum += i
end
end
sum
end
code 2 — not using i’s and j’s in a while loop
def even_fibonacci_sum(limit)
arr = [1 , 2]
while arr.last < limit
sum = arr[-2] + arr.last
break if sum > limit
arr << sum
end
sum = 0
arr.each do |i|
sum += i if i % 2 == 0
end
sum
end
* code 3 * not using i’s and j’s in a loop do
def even_fibonacci_sum(limit)
arr = [1 , 2]
loop do
sum = arr[-2] + arr.last
break if sum > limit
arr << sum
end
sum = 0
arr.each do |i|
sum += i if i % 2 == 0
end
sum
end
TL; DR: Refactoring is pretty! Code 1 can be refactored as code 2 or code 3.
Originally published at sofiama.github.io on November 10, 2014.