Here’s the second problem from Project Euler:

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.

Before seeing this problem, I had only heard of the Fibonacci numbers a couple times, and had never actually known what they were. It seemed simple enough from the problem description: each subsequent term is equal to the sum of the previous two. Here’s what I came up with:

``` ruby problem2.rb

def fibonacci_evens_sum(limit) arr = [] a,b = 0,1 while a < limit arr « a a, b = b, a + b end

sum = {|num| num % 2 == 0}.reduce(:+) puts sum end


#Answer is 4613732 ``` The fibonacci_evens_sum method allows for one argument that specifies the limit of the even fibonacci numbers. While a is less than the specified limit, the value of a is replaced with the value of b. Then the value of b is replaced with the the value of a + b. These two steps create the Fibonacci sequence, by creating a list of numbers in which each subsequent number is equal to the sum of the previous two.

When the limit is reached, the select method returns an array of num’s that are divisible by 2 with no remainder. The reduce method then adds every item in the returned array together. reduce is just an alias for the inject method, so they can be used interchangeably.


I looked through the forums, and compared the speed of my solution to another with benchmark. ``` ruby Other Solution class EvenFibonacci attr_accessor :evenSequence

def initialize
  @evenSequence = []

def get_even_fibonacci_sum(number_to_operate)
  value = 0

  if number_to_operate <= 1
    return number_to_operate
    value = (get_even_fibonacci_sum(number_to_operate - 1) + get_even_fibonacci_sum(number_to_operate - 2)) 

  if value % 2 == 0 && !@evenSequence.include?(value) && value < 4000000
    @evenSequence << value 

  return value
end   end

fib_find = print “#{fib_find.get_even_fibonacci_sum(34)} \n#{fib_find.evenSequence.reduce(:+)}”

end Here's the speed comparison: plain #My Solution 0.000000 0.000000 0.000000 ( 0.000103)

#Other solution 3.900000 0.000000 3.900000 ( 3.908138) ``` A couple things about the other solution stick out to me. There is a lot of unnecessary code. You don’t need to create a whole class and include an initialize method. The creation of a new EvenFibonacci object slows it down considerably.

As I’ve been learning Ruby, I’ve seen that the community is very opinionated on how things should be done, and for good reason. When you don’t follow the Ruby “style” of programming, things can get a great deal slower.