-
-
Save aeriksson/d27ffc64899a0face006 to your computer and use it in GitHub Desktop.
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
; from clojure.contrib.lazy-seqs | |
(def primes | |
(lazy-cat [2 3 5 7] | |
(let [primes-from (fn primes-from [n [f & r]] | |
(if (some #(zero? (rem n %)) | |
(take-while #(<= (* % %) n) primes)) | |
(recur (+ n f) r) | |
(lazy-seq (cons n (primes-from (+ n f) r))))) | |
wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2 | |
6 4 6 8 4 2 4 2 4 8 6 4 6 2 4 6 | |
2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])] | |
(primes-from 11 wheel)))) | |
; adapted from http://stackoverflow.com/a/10733621 | |
(def primes2 | |
(lazy-cat [2 3 5 7] | |
(let [update-map (fn update-map [step-map candidate step] | |
(assoc step-map | |
(first (filter #(not (contains? step-map %)) (take-nth step (drop (+ candidate step) (range))))) | |
step)) | |
sieve (fn sieve [c step-map p primes] | |
(if (contains? step-map c) | |
(recur (+ 2 c) (update-map (dissoc step-map c) c (get step-map c)) p primes) | |
(if (< c (* p p)) | |
(lazy-seq (cons c (sieve (+ 2 c) step-map p primes))) | |
(recur (+ 2 c) (update-map step-map c (* 2 p)) (first primes) (rest primes)))))] | |
(sieve 9 {} 3 (drop 2 primes2))))) | |
(time (doall (take 2000 primes))) ; "Elapsed time: 46.735 msecs" | |
(time (doall (take 2000 primes2))) ; "Elapsed time: 4350.666 msecs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment