Created
August 6, 2009 13:28
-
-
Save cgrand/163309 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
; http://projecteuler.net/index.php?section=problems&id=27 | |
(defn lazy-primes3 [] | |
(letfn [(enqueue [sieve n step] | |
(let [m (+ n step)] | |
(if (sieve m) | |
(recur sieve m step) | |
(assoc sieve m step)))) | |
(next-sieve [sieve candidate] | |
(if-let [step (sieve candidate)] | |
(-> sieve | |
(dissoc candidate) | |
(enqueue candidate step)) | |
(enqueue sieve candidate (+ candidate candidate)))) | |
(next-primes [sieve candidate] | |
(if (sieve candidate) | |
(recur (next-sieve sieve candidate) (+ candidate 2)) | |
(cons candidate | |
(lazy-seq (next-primes (next-sieve sieve candidate) | |
(+ candidate 2))))))] | |
(cons 2 (lazy-seq (next-primes {} 3))))) | |
(defn results [a b] (map #(+ b (* % (+ a %))) (iterate inc 0))) | |
;would it be faster to go incremental ? Z80 style | |
;(n+1)^2 + a(n+1) + b = n^2 + 2n + 1 + an + a + b = (n^2 + an + b) + 2n + 1 + a | |
(def prime? | |
(let [primes (lazy-primes3)] | |
(memoize (fn [n] (some #{n} (take-while #(<= % n) primes)))))) | |
(defn step [[a b [x & xs] :as v]] | |
(when (prime? x) | |
(assoc v 2 xs))) | |
(defn result [n] | |
(let [r (range (inc (- n)) n) | |
seeds (for [a r b r] [a b (results a b)]) | |
l (last (take-while seq | |
(iterate #(for [x % :let [x (step x)] :when x] x) seeds)))] | |
; (iterate #(remove nil? (map step %)) seeds)))] | |
(map #(take 2 %) l))) | |
(result 42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment