Created
November 18, 2013 20:13
-
-
Save ray1729/7534528 to your computer and use it in GitHub Desktop.
Ring of Primes http://coj.uci.cu/24h/problem.xhtml?abb=1196
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
(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