Search code examples
clojure

Clojure Integer Overflow Using reduce function


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 

Solution

  • 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