DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Prime Number Generator In Clojure

08.27.2010
| 3170 views |
  • submit to reddit
        My first attempt at Clojure. An implementation of the Sieve of Eratosthenes

(ns squarepegsystems.primes
  (:use clojure.test))  

(defn sieve  [maxvalue]
    (loop [primes [] composites (set[]) x 2]
      (if (= x (+ maxvalue 1))
        primes
        (if (=(count(filter  #(= x %) composites)) 0)
          (recur
            (concat primes [x])
            (set( concat composites (range (* 2 x) (+ maxvalue 1) x)))
            (inc x) )
          (recur  (concat primes []) (concat composites []) (inc x) )
        )))
  ) 

(deftest testsieve

  (is (= [] (sieve 1)))
  (is (= [2] (sieve 2)))
  (is (= [2 3] (sieve 3)))
  (is (= [2 3] (sieve 4)))
  (is (= [2 3 5] (sieve 5)))
  (is (= [2 3 5 7] (sieve 10)))

  (is (= [2 3 5 7 11 13 17 19] (sieve 20)))
  )


(run-tests)