-
-
Save jneira/948184 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
;; jneira's solution to http://4clojure.com/problem/67 | |
(fn primes [n] | |
(letfn | |
[(next-prime | |
[prs nxt] | |
(if (empty? (filter #(= 0 (mod nxt %)) prs)) | |
(conj prs nxt) | |
(recur prs (inc nxt))))] | |
(->> (iterate | |
(fn [prs] (next-prime prs (inc (last prs)))) [2]) | |
(take n) | |
(last)))) | |
(fn primes2 [n] | |
(last | |
(take | |
n | |
(map first | |
((fn iter-when [pred f x] | |
(let [iter #(iter-when pred f %) | |
n-cons (f x)] | |
(if (pred n-cons x) | |
(cons x (lazy-seq (iter n-cons))) | |
(iter n-cons)))) | |
#(not= (first %1) (first %2)) | |
(fn [[prs nxt :as c]] | |
(let [n-prs (if (empty? (filter #(zero? (mod nxt %)) prs)) | |
(conj prs nxt) prs)] | |
[n-prs (inc nxt)])) | |
[[2] 3]))))) | |
(defn primes3 [n] | |
(let | |
[next-prime | |
(fn [prs] | |
(letfn | |
[(aux [[f & r :as c] nxt] | |
(cond | |
(empty? c) (conj prs nxt) | |
(zero? (mod nxt f)) (recur prs (inc nxt)) | |
:else (recur (take-while #(< % (quot nxt f)) r) | |
nxt)))] | |
(aux prs (inc (last prs)))))] | |
(->> (iterate next-prime [2]) | |
(take n) | |
(last)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment