Monday, June 16, 2014

Even Fibonacci numbers - Project Euler Problem - Clojure solution


Even Fibonacci numbers

Today we will look at a Project Euler problem. The problem is  - By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. 
As would be evident from looking at the problem statement, we first need to write a way of calculating Fibonacci numbers. As has been the tradition, let's first solve it in Python -


       >>> def fibonacci():
               x,y = 0,1
               while True:
                   yield x
                   x, y = y, x+y

                  
       >>> def even(number):
               if not number % 2 :
                   return True
               return False

and here is the invocation

       >>> def euler2():
              fgen = fibonacci()
              nextValue = fgen.next()
              answer = 0
              while nextValue < 4000000 :
                   if (even (nextValue)):
                       answer += nextValue
                   nextValue = fgen.next()

               return answer

       >>> euler2()

       4613732

Our rigor on factorials pays off and we are good to go with a definition straight away -

(def fib-seq

     (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))

This generates a lazy sequence of fibonacci numbers. Next, we would want to filter out the even numbers and take the numbers which remain less than 4000000. Finally, we apply the reduction of + function over all such numbers.
(reduce +
        (take-while (partial >= 4000000)
                      (filter even? fib-seq)
        )

)

And running this on a REPL generates the same answer again - 4613732.




No comments:

Post a Comment