Skip to content

Instantly share code, notes, and snippets.

@jgilless
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgilless/16a2327827c93f278971 to your computer and use it in GitHub Desktop.
Save jgilless/16a2327827c93f278971 to your computer and use it in GitHub Desktop.
Ruby solution for Project Euler problem 2
# https://projecteuler.net/problem=2
puts "Find the sum of even valued Fibonnaci terms which values do not exceed:"
STDOUT.flush #clears the buffer
num = Integer(gets.chomp)
def fibonacci(max_num)
fibonacci = [1,2] #first two numbers of the sequence
while fibonacci[-2] + fibonacci[-1] < max_num
fibonacci << fibonacci[-2] + fibonacci[-1] # next num in sequence
end
fibonacci #return
end
def sum_fibonacci(max_num)
sum = 0
fibonacci(max_num).each do |n|
sum = sum + n if n.even? #Add if n is even
end
sum #return
end
puts "Sum of even Fibonacci numbers up to #{num} = " + sum_fibonacci(num).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment