Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created July 9, 2010 15:21
Show Gist options
  • Save abhin4v/469600 to your computer and use it in GitHub Desktop.
Save abhin4v/469600 to your computer and use it in GitHub Desktop.
(ns net.abhinavsarkar
(:use
[clojure.contrib.math :only (sqrt ceil)]
[clojure.contrib.import-static]))
(import-static java.lang.Integer parseInt)
(declare primes)
(defn- divisible? [x y] (zero? (mod x y)))
(defn prime-divisors [n]
(filter (partial divisible? n)
(take-while #(<= % (ceil (sqrt n))) primes)))
(def prime?
(memoize
(fn [n]
(cond
(= n 1) false
(some #(= n %) [2 3 5 7]) true
(some (partial divisible? n) [2 3 5 7]) false
(not-any? #(zero? (mod (% n) 6)) [inc dec]) false
:else (empty? (prime-divisors n))))))
(def primes
(let [odds (iterate #(+ % 2) 3)]
(cons 2 (filter prime? odds))))
(defn primes-between [start, end]
(let [
start-012?
(some #(= start %) [0 1 2])
first-candidate
(cond
start-012? 3
(prime? start) start
(divisible? start 2) (inc start)
:else (+ start 2))
candidates
(iterate #(+ % 2) first-candidate)
real-candidates
(if start-012?
(cons 2 candidates)
candidates)]
(filter prime?
(take-while #(<= % end) real-candidates))))
(defn main []
(let [[x y] (map #(parseInt %) *command-line-args*)]
(doseq [p (primes-between x y)] (println p))))
(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment