Created
January 6, 2012 18:51
-
-
Save vinibaggio/1571889 to your computer and use it in GitHub Desktop.
Prime numbers
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
;; The input is: | |
;; first line: the number of test cases | |
;; next lines are the limits m n such as prime numbers are in [m;n] | |
;; Algorithm used: Sieve of Erasthotenes | |
(use '[clojure.set :only (difference)]) | |
(defn mark | |
([all n limit] | |
(mark all n n limit)) | |
([all n step limit] | |
(let [current (+ n step) | |
unmarked (disj all current)] | |
(if (> n limit) | |
all | |
(recur unmarked current step limit))))) | |
(defn mark-all | |
([all limit] | |
(mark-all all 2 limit)) | |
([all current limit] | |
(let [unmarked (mark all current limit) | |
marked (difference all unmarked) | |
next-val (first (filter #(> % current) unmarked))] | |
(if (> (* current current) limit) | |
unmarked | |
(mark-all unmarked next-val limit))))) | |
(defn primes [start end] | |
(let [all (apply sorted-set (range 2 (+ end 1)))] | |
(filter #(>= % start) (mark-all all end)))) | |
(let [times (Integer/parseInt (read-line))] | |
(dotimes [_ times] | |
(let [line (map #(Integer/parseInt %) (re-seq #"\w+" (read-line)))] | |
(println (reduce #(format "%s\n%d" %1 %2) (apply primes line))) | |
(printf "\n")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment