(ns primes.primes) (defn debug-on? [] "debug print statements :)" false) (defn sieve [n] (let [n (int n)] "Returns a list of all primes from 2 to n (from: http://paste.lisp.org/display/69952)" (let [root (int (Math/round (Math/floor (Math/sqrt n))))] (loop [i (int 3) a (int-array n) result (list 2)] (if (>= i n) (reverse result) (recur (+ i (int 2)) (if (< i root) (loop [arr a inc (+ i i) j (* i i)] (if (>= j n) arr (recur (do (aset arr j (int 1)) arr) inc (+ j inc)))) a) (if (zero? (aget a i)) (conj result i) result))))))) (defn get-primes "take n primes from the set of all primes" [n] (take n (sieve (* n n)))) (defn nary-dec "map base_n -> decimal (for placement of values in the matriies" [n num] (int (reduce + (map-indexed (fn [i v] (* (Math/pow n i) v)) (reverse num))))) (defn psq [n] "get the next (i,j,value) sequence of primes for the matrix" (let [primes (get-primes (* n n))] (for [i (range n) j (range n)] [i j (nth primes (nary-dec n (list i j)))]))) (defn amatrix "make a matrix given (i,j,value) tuples" [i_j_v-list] (if (zero? (count i_j_v-list)) [[]] (let [size (inc (first (last i_j_v-list)))] (vec (for [u (range size)] (vec (for [v (range size)] (last (nth i_j_v-list (nary-dec size [u v])))))))))) (defn gpm "get n x n prime matrix" [n] (amatrix (psq n))) (defn sumrows [matrix] (map (partial reduce +) matrix)) (defn summat "sum of a matrix is the sum of the sum of each row" [matrix] (reduce + (sumrows matrix))) (defn get-pair [n] [(gpm n) (gpm (inc n))]) (defn op-pair [op pair] (op (summat (first pair)) (summat (second pair)))) (defn reduce-primes-with [op n] (map (partial op-pair op) (map get-pair (range (inc n))))) (println (reduce-primes-with * 15))