Skip to content

Instantly share code, notes, and snippets.

@jtallant
Created June 25, 2012 13:51
Show Gist options
  • Save jtallant/2988749 to your computer and use it in GitHub Desktop.
Save jtallant/2988749 to your computer and use it in GitHub Desktop.
Project Euler Problem 2
# Project Euler 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.
# The longer way (so you can see what is going on)
# We put the even valued terms into an array and then use
# inject to add all the items together giving the sum
# of the even-valued terms
first = 0
second = 1
i = 0
sequence = []
while i <= 4000000
i = first + second
sequence << i if i % 2 == 0
# puts sequence
first = second
second = i
end
puts "The sum of the even valued terms is #{sequence.inject(:+)}"
# The shorter way
# sum the even valued terms as we move
# through the loop
first = 0
second = 1
i = 0
sum = 0
while i <= 4000000
i = first + second
sum += i if i % 2 == 0
first = second
second = i
end
puts sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment