Last active
December 18, 2015 02:39
-
-
Save martintrojer/5712098 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
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-filter [in out prime] | |
(go | |
(loop [i (<! in)] | |
(when-not (zero? (mod i prime)) | |
(>! out i)) | |
(recur (<! in))))) | |
(let [ch (chan)] | |
(go (loop [i 2] (>! ch i) (recur (inc i)))) | |
(loop [ch ch, i 100] | |
(when (pos? i) | |
(let [prime (<!! ch) | |
next (chan)] | |
(println prime) | |
(prime-filter ch next prime) | |
(recur next (dec i)))))) |
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-seq [[fst & rst]] | |
(lazy-seq | |
(cons fst (sieve-seq (remove #(zero? (mod % fst)) rst))))) | |
(def primes (sieve-seq (iterate inc 2))) | |
(take 100 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
def sieve(s: Stream[Int]): Stream[Int] = { | |
s.head #:: sieve(s.tail.filter(_ % s.head != 0)) | |
} | |
val primes = sieve(Stream.from(2)) | |
primes.take(100).toList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment