Skip to content

Instantly share code, notes, and snippets.

@jgilless

jgilless/euler2.rb

Last active Aug 29, 2015
Embed
What would you like to do?
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