Skip to content

Instantly share code, notes, and snippets.

@mingca
Last active June 6, 2018 20:55
Show Gist options
  • Save mingca/3430461a4fe96f1a5e5800c40dd75aa8 to your computer and use it in GitHub Desktop.
Save mingca/3430461a4fe96f1a5e5800c40dd75aa8 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."
# Instructions:
# Construct a solution using Ruby that could be incorporated into a larger project. Solutions will be evaluated for readability, testability, and extensibility.
# Calculate sum of even-valued terms in fibonacci
class Fibonacci
attr_accessor :limit
def initialize(limit = 4_000_000)
@limit = limit
end
def even_sum
@a = 1
@b = 2
sum = 0
loop do
sum += @b if @b.even?
advance
break if @b > limit
end
sum
end
private
def advance
@a, @b = @b, @a + @b
end
end
puts Fibonacci.new.even_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment