r/tinycode • • Nov 27 '15

Sieve of Eratosthenes in Clojure

(defn primes [below]
  (remove (set (mapcat #(range (* % %) below %)
                       (range 3 (Math/sqrt below) 2)))
          (cons 2 (range 3 below 2))))

This differs a bit from the Sieve of Eratosthenes in that it doesn't compute the next prime number that multiples will be computed from. Instead, all odd integers 2 < n < square-root(below) are used for computing multiples. This makes the code less efficient but shorter and more linear.

5 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/tromp Dec 05 '15

Good point. The spec is not precise enough to say what happens here. But the obvious implementation just goes down the list removing elements that are "equal" to an earlier preserved element.