4

Unfortunately my code is giving me an Integer Overflow exception.

(defn even-fib-sum [n]
   (reduce + 
      (filter even? 
         (take n (map first (iterate (fn [[x y]] [y (+ x y)]) [0 1]))))))

The problem occurs when I call the function and pass the value 4000000

(even-fib-sum 4000000) -> throws exception

(even-fib-sum 40) -> 82790070 

1 Answer 1

7

use +' instead of + to get auto promoting addition to bigintegers

(reduce +' 
   (filter even? 
     (take n (map first (iterate (fn [[x y]] [y (+' x y)]) [0 1])))))

Cloujure uses longs by default and treats overflow as an error. In the very early days of the language auto-promotion was the default until it was generally agreed that overflowing a long was almost always a bug except in the cases where people explicitly know they want it so it was changed and the +', *', and -' operators where added for the cases where people explicitly choose them

Sign up to request clarification or add additional context in comments.

1 Comment

I believe that +' should be used in the last line of the function as well; otherwise it overflows at (even-fib-sum 93).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.