in Programming

Project Euler Problem 2 Solution: Clojure

Problem 2 Description, from Project Euler

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

Solutions

My first attempt

The trickiest thing for me was figuring out how to write the fibonacci function in an elegant way. I know that with functional languages, recursion is supposed to be super elegant, and my solution was anything but.

    (defn problem02
        []
        (defn fib
            [termCount]
            (defn fib-help
                [termCount, terms]
                (def rterms (reverse terms))
                (def lst (first rterms))
                (def nlst (first (rest rterms)))
                (if (< (count terms) termCount)
                    (fib-help
                        termCount
                        (reverse (cons (+ lst nlst) rterms))
                        )
                    terms
                    )
                )
            (fib-help termCount, `(1, 2))
            )
        (reduce + (filter
            #(and
                (< % 4000000)
                (even? %)
                )
            (fib 200)
            ))

)
(problem02)


A solution by another person

The site I linked to in the previous article as a much more elegant solution. I really had trouble figuring out how to do an elegant Fibonacci algorithm, although I knew that mine was inelegant!

   (defn e2 [limit]
     (let [fibs2 (lazy-cat [0 1]
                           (map + fibs2 (rest fibs2)))]
       (reduce + (filter #(zero? (mod % 2))
                         (take-while #(< % limit) fibs2)))))

I love the user of lazy-cat. I was trying to search for how to do this, but wasn’t sure what this was called. I only knew that the iterate function used something like this (I guess I could’ve checked it’s source). I find the use of map interesting, but confusing because it seems as if fibs2 would return a list and that there should somehow be duplicate values in that list. I’m sure I will come to understand more later.

Comments are closed.