Instantly share code, notes, and snippets.

# borkdude/Factors Created May 23, 2010

Euler Problem 5 in Clojure
 (defn prime? [n] (cond (= n 2) true (= n 3) true :else (not-any? #(zero? (mod n %))(range (int (Math/sqrt n)) n)))) (def my-primes (filter prime? (iterate inc 2))) (defn update-or-insert [m k f d] (if (contains? m k) (update-in m [k] f) (assoc m k d))) (defn factors ([n] (factors n (sorted-map))) ([n fs] (cond (= n 0) fs (= n 1) fs (prime? n) (update-or-insert fs n inc 1) :else (let [f (first (for [p my-primes :when (zero? (mod n p))] p)) ndiv (quot n f)] (recur ndiv (update-or-insert fs f inc 1)))))) (defn my-power ([x n] (my-power x n 1)) ([x n r] (if (= n 0) r (recur x (dec n) (* r x))))) ; find the common set of factors for a range of numbers (defn div-by-all [n] (reduce * (map #(my-power (first %) (second %)) (apply merge-with max (map factors (range 2 (inc n))))))) (div-by-all 20) 232792560 (div-by-all 200) 337293588832926264639465766794841407432394382785157234228847021917234018060677390066992000