Skip to content

Instantly share code, notes, and snippets.

@borkdude borkdude/Factors
Created May 23, 2010

What would you like to do?
Euler Problem 5 in Clojure
(defn prime? [n]
(cond (= n 2) true
(= n 3) true
(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)
(let [f (first
(for [p my-primes
:when (zero? (mod n 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)
(div-by-all 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.