Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Integer Overflow Using reduce function

Tags:

clojure

I am currently going through the project euler problems using Clojure. The second question requires you to sum the first 4000000 fibonaci numbers. 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 
like image 271
insudo Avatar asked Mar 18 '23 12:03

insudo


1 Answers

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

like image 97
Arthur Ulfeldt Avatar answered Mar 24 '23 21:03

Arthur Ulfeldt