Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created November 18, 2013 20:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ray1729/7534528 to your computer and use it in GitHub Desktop.
Save ray1729/7534528 to your computer and use it in GitHub Desktop.
(ns ring-of-primes
(:gen-class))
(defn prime?
[n]
(and (> n 1)
(not-any? #(zero? (mod n %)) (range 2 (inc (int (Math/sqrt n)))))))
(defn neighbours
[xs ring]
(for [x xs :when (prime? (+ x (last ring)))]
[(disj xs x) (conj ring x)]))
(defn lazy-ring-of-primes
[stack]
(when-let [[xs ring] (peek stack)]
(if (empty? xs)
(if (prime? (+ (first ring) (last ring)))
(cons ring (lazy-seq (lazy-ring-of-primes (pop stack))))
(recur (pop stack)))
(recur (reduce conj (pop stack) (neighbours xs ring))))))
(defn ring-of-primes
[n]
(lazy-seq (lazy-ring-of-primes [[(into #{} (range 2 (inc n))) [1]]])))
(defn -main [& args]
(let [[n m] (map #(Integer/parseInt %) args)]
(when-not n (throw (Exception. "Size of ring not specified")))
(doseq [ring (if m (take m (ring-of-primes n)) (ring-of-primes n))]
(println ring))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment