I'm learning clojure and going through the clojure-koan exercises. One of the exercises is about implementing a factorial function. While I was playing around I noticed:
My recursive implementation seems to work for large numbers:
(defn factorial-1 [n]
(loop [n n f 1]
(if (= n 1)
f
(recur (dec n) (* f n)))))
Calling (factorial-1 1000N) in a REPL yields a number: 402387260077093773...
However when I try the following lazy sequence approach:
(defn factorial-2 [n]
(reduce * 1 (range 1 (inc n))))
Calling (factorial-2 1000N) in a REPL yields an error:
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1388)
Why does the seemingly lazy sequence approach result in an integer overflow error?