Created
August 30, 2013 06:10
-
-
Save skatenerd/6386766 to your computer and use it in GitHub Desktop.
euler-5
This file contains hidden or 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 max-merge [first second] | |
(reduce | |
(fn [factors-so-far current-key] | |
(let [higher-value (max (get first current-key 0) (get second current-key 0))] | |
(assoc factors-so-far current-key higher-value))) | |
{} | |
(clojure.set/union (set (keys first)) (set (keys second))))) | |
(def naturals (iterate inc 1)) | |
(defn divides? [bottom top] | |
(zero? (mod top bottom))) | |
(defn assoc-if | |
[m key val should-assoc] | |
(if should-assoc (assoc m key val) m)) | |
(defn power-for-divisor [base top] | |
(let [too-much-power (remove #(divides? (Math/pow base %) top) naturals) | |
first-too-high-exponent (first too-much-power)] | |
(dec first-too-high-exponent))) | |
(defn factor [n] | |
(loop [remaining n factors {} divisor 2] | |
(if (= remaining 1) | |
factors | |
(let [power-for-divisor (power-for-divisor divisor remaining) | |
amount-to-cut-out (Math/pow divisor power-for-divisor)] | |
(recur | |
(int (/ remaining amount-to-cut-out)) | |
(assoc-if factors divisor power-for-divisor (> power-for-divisor 0)) | |
(inc divisor)))))) | |
(defn unfactor [factorization] | |
(reduce | |
(fn [current-total [k v]] | |
(* current-total (Math/pow k v))) | |
1 | |
factorization)) | |
(defn get-answer [] | |
(unfactor (reduce max-merge (map factor (range 2 21))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment