1

Possible Duplicate:
Recursive function causing a stack overflow

I wrote a function calculating all the primes below a given natural number, using the Sieve of Eratosthenes. It returns the whole prime sequence.

(defn primes-below [n]
    (loop [primes [] source (range 2 n)]
        (if (empty? source)
            primes
            (recur
                (conj primes (first source))
                (filter #(not (= (rem % (first source)) 0)) source)))))

It works fine till n's magnitude of 10000. However, at n = 100000 it results in Out of Memory exception. Why is that? I thought the arguments of loop/recur aren't stored in the stack. How can I fix that?

Community
  • 1
  • 1
Ivan Krechetov
  • 18,802
  • 8
  • 49
  • 60

0 Answers0