I learn clojure and look through the clojure -koan exercises. One exercise is the implementation of a factorial function . When I played, I noticed:
The recursive implementation seems to work for large numbers:
(defn factorial-1 [n] (loop [nnf 1] (if (= n 1) f (recur (dec n) (* fn)))))
The call (factorial-1 1000N) in the REPL gives the number: 402387260077093773...
However, when I try to use the following lazy approach:
(defn factorial-2 [n] (reduce * 1 (range 1 (inc n))))
Calling (factorial-2 1000N) in REPL gives an error:
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1388)
Why does the seemingly lazy sequence approach lead to an integer overflow error?
source share