Last active
December 22, 2015 06:29
-
-
Save gfredericks/6431802 to your computer and use it in GitHub Desktop.
A lazy primes function in Clojure using only addition and comparisons.
This file contains hidden or 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 | |
"Returns a lazy sequence of primes." | |
[] | |
(cons 2 | |
(lazy-seq | |
(let [local-primes (->> (primes) | |
(map (juxt identity #(apply + (repeat % %)))))] | |
(->> (iterate #(+ % 2) 3) | |
(remove (fn [n] | |
(->> local-primes | |
(take-while #(<= (second %) n)) | |
(some (fn [[d]] | |
(->> d | |
(iterate #(+ % %)) | |
(take-while #(<= % n)) | |
(reverse) | |
(reduce #(let [x (+ %1 %2)] | |
(if (> x n) %1 x)) | |
0) | |
(= n)))))))))))) | |
;; user> (time (nth (primes) 10000)) | |
;; "Elapsed time: 7453.629671 msecs" | |
;; 104743 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment