Created
May 23, 2010 18:44
-
-
Save borkdude/411154 to your computer and use it in GitHub Desktop.
Euler Problem 5 in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment