Skip to content

Instantly share code, notes, and snippets.

@pjc
Created July 1, 2012 22:32
Show Gist options
  • Save pjc/3029863 to your computer and use it in GitHub Desktop.
Save pjc/3029863 to your computer and use it in GitHub Desktop.
Euler Project in Ruby - Problem 2
# Create Fibonnaci Array
a = [1,2]
upto = 4_000_000
while a[-2] + a[-1] < upto
a << a[-2] + a[-1]
end
# Create sum of even Fibonnaci numbers
sum = 0
a.each { |x| sum+= x if x.even? }
puts "The result is #{sum}"
@nick-brown
Copy link

I think the initial array should be [1,1] to get the correct sequence. 1, 1, 2, 3, 5... etc

@Aiishe
Copy link

Aiishe commented Apr 9, 2015

Here's my solution. Personally find it easier to understand than the one given

a = 0 #first fibonnaci number
b = 1 #second fibonnaci number
c = 0 #current fibonnaci number
sumevens = 0 #sum of even fibonnaci numbers less than 4,000,000

while c <= 4000000
    c = a + b
    a = b
    b = c
    sumevens += c if c % 2 == 0 
end

puts sumevens

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment