Last active
December 22, 2015 19:39
-
-
Save blinsay/6520793 to your computer and use it in GitHub Desktop.
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
(defmacro divides? | |
"Return true if y divides x. Expands to (= 0 (mod x y))" | |
[x y] | |
`(zero? (mod ~x ~y))) | |
(defn prime? | |
"Check to see if a number is prime. Naive" | |
[n] | |
(let [r (inc (Math/floor (Math/sqrt n)))] | |
(nil? (some #(divides? n %) (range 2 r))))) | |
(defn prime-divisors | |
"A lazy-seq of all of the prime divisors of n between 2 and sqrt(n)" | |
[n] | |
(let [r (inc (Math/floor (Math/sqrt n)))] | |
(filter prime? (filter #(divides? n %) (range 2 r))))) | |
(defn prime-factors | |
"Generate the prime factorization of n as a seq" | |
[n] | |
((fn [x accum] | |
(if (prime? x) | |
(cons x accum) | |
(let [d (first (prime-divisors x))] | |
(recur (/ x d) (cons d accum))))) | |
n [])) | |
(defn counts | |
"Given a collection, returns a map from items in the collection to the number | |
of times they occur" | |
[xs] | |
(reduce #(assoc %1 %2 (inc (get %1 %2 0))) {} xs)) | |
(defn get-answer [] | |
(let [factor-counts (map #(counts (prime-factors %)) (range 1 (inc n)))] | |
(reduce-kv #(apply * %1 (repeat %3 %2)) 1 (apply merge-with max factor-counts))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
merge-with
is pretty cool. good to know that exists.