adamjmarkham
adamjmarkham

Reputation: 2164

Fibonacci Sequence using loop and recur

I am doing the Project Euler challenge in Clojure and I want to find the sum of all the even numbers in a fibonacci sequence up to a certain number.

The code for a function that does this is below. I know there are quicker and easier ways of doing this, I am just experimenting with recursion using loop and recur. However the code doesn't seem to work it never returns an answer.

(defn fib-even-sum [upto]
  (loop [previous 1 nxt 1 sum 0]
    (if (or (<= upto 1) (>= nxt upto))
     sum)
    (if (= (mod nxt 2) 0)
       (recur nxt (+ previous nxt) (+ sum nxt))
       (recur nxt (+ previous nxt) sum))))

I was not sure if I could do recur twice in the same loop or not. I'm not sure if this is causing the problem?

Upvotes: 4

Views: 1820

Answers (1)

Paul Lam
Paul Lam

Reputation: 1819

You have a misplaced closing paren in the first IF (after sum)...

(defn fib-even-sum [upto]
  (loop [previous 1 nxt 1 sum 0]
    (if (or (<= upto 1) (>= nxt upto))
        sum
        (if (= (mod nxt 2) 0)
           (recur nxt (+ previous nxt) (+ sum nxt))
           (recur nxt (+ previous nxt) sum)))))

Now it works and fast

Upvotes: 5

Related Questions