Skip to content

Instantly share code, notes, and snippets.

@devstopfix
Created June 25, 2015 19:30
Show Gist options
  • Save devstopfix/7f4fbeea82749767c9c6 to your computer and use it in GitHub Desktop.
Save devstopfix/7f4fbeea82749767c9c6 to your computer and use it in GitHub Desktop.
;
; Generate a table of the products of prime numbers
;
(defn √ [x]
"Integer square root of x"
(int (Math/sqrt x)))
(defn prime? [x]
"Return true if x is a prime number, using naïve trial division algorithm."
(->>
(range 2 (inc (√ x)))
(map (fn [d] (/ x d)))
(not-any? integer?)))
(defn prime-numbers []
"A lazy seq of prime numbers"
(lazy-seq
(->>
(range)
(drop 2)
(filter prime?))))
(defn products [xs]
"Return a table of xs by xs and their products."
(for [y xs]
(for [x xs]
(* x y))))
(defn format-row [row]
(apply str
(map (clojure.core/format "%8d" %) row)))
(defn format-tbl [tbl]
"Format a list of numbers and seq of seqs into a table"
(clojure.string/join "\n"
(map format-row tbl)))
(->>
(prime-numbers)
(take 6)
(products)
(format-tbl)
(println))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment