Skip to content

Instantly share code, notes, and snippets.

@vinibaggio
Created January 6, 2012 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinibaggio/1571889 to your computer and use it in GitHub Desktop.
Save vinibaggio/1571889 to your computer and use it in GitHub Desktop.
Prime numbers
;; 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