Created
July 1, 2012 14:51
-
-
Save tnoda/3028665 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn prime? [n] | |
(every? #(pos? (rem n %)) (range 2 (Math/sqrt (inc n))))) | |
(defn naive-primes [n] | |
(filter prime? (range 2 (inc n)))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn primes' | |
([^long n] | |
(let [not-prime (doto (boolean-array (inc n)) | |
(aset 0 true) | |
(aset 1 true)) | |
primes (long-array (inc n))] | |
(loop [p (int 0), i (int 2)] | |
(if (<= i n) | |
(if (aget ^booleans not-prime i) | |
(recur p (inc i)) | |
(do | |
(aset ^longs primes p i) | |
(loop [j (* 2 i)] | |
(when (<= j n) | |
(aset ^booleans not-prime j true) | |
(recur (+ j i)))) | |
(recur (inc p) (inc i)))) | |
(take p primes)))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn sieve [[xs ps]] | |
(let [[p & more] xs] | |
[(remove #(zero? (rem % p)) xs) (cons p ps)])) | |
(defn primes [n] | |
(if (< n 2) | |
[] | |
(->> [(range 2 (inc n)) nil] | |
(iterate sieve) | |
(drop-while #(< (ffirst %) (Math/sqrt n))) | |
first | |
(apply concat)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know it's 3.5 years later, but in the third example, I believe your drop-while condition should be <=, rather than <.
Try feeding it a square of a prime.