Hi guys, playing around with different ways of creating primes. The
following implementation is probably not very efficient, but it does
seem to be correct. The problem is that when run it gives a
java.lang.StackOverflowError.

(defn primes[num]
  (let [possible (range 2 num)]
    (loop [current 2 rst possible]
      (if-not current rst
          (recur
            (first (filter #(< current %) rst))
            (remove
              (fn [el] (and
                         (> el current)
                         (= (rem el current) 0)))
                rst))))))

(primes 20)
=> (2 3 5 7 11 13 17 19)

(primes 80000)
=> (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
89 97 101 103 107 109 113 127 131 137 139 149 151 157 ......)

(primes 90000)
=> java.lang.StackOverflowError

It seems there is quite a tight loop that is responsible for the overflow:
....
        at clojure.core$filter$fn__3718.invoke(core.clj:2130)
        at clojure.lang.LazySeq.sval(LazySeq.java:42)
        at clojure.lang.LazySeq.seq(LazySeq.java:56)
        at clojure.lang.RT.seq(RT.java:450)
        at clojure.core$seq.invoke(core.clj:122)
        at clojure.core$filter$fn__3718.invoke(core.clj:2130)
        at clojure.lang.LazySeq.sval(LazySeq.java:42)
        at clojure.lang.LazySeq.seq(LazySeq.java:56)
        at clojure.lang.RT.seq(RT.java:450)
        at clojure.core$seq.invoke(core.clj:122)
        at clojure.core$filter$fn__3718.invoke(core.clj:2130)
....

What am I doing wrong here, will filter/remove or something else give
StackOverflowError when used incorrectly?

Cheers,
Alf

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to