Skip to content

Instantly share code, notes, and snippets.

@gfredericks
Last active December 22, 2015 06:29
Show Gist options
  • Save gfredericks/6431802 to your computer and use it in GitHub Desktop.
Save gfredericks/6431802 to your computer and use it in GitHub Desktop.
A lazy primes function in Clojure using only addition and comparisons.
(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