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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With