Monday, August 25, 2014

Euler Project: Problem 3 in Clojure

This is my solution in Clojure to the third problem from Euler project:

(def factor?
(comp zero? rem))
(defn prime-factors [n]
(loop [n n prime 2 factors #{}]
(cond
(= n 1) factors
(factor? n prime) (recur (/ n prime) prime (conj factors prime))
:else (recur n (inc prime) factors))))
(prime-factors 35) ; #{5 7}
(prime-factors 24) ; #{2 3}
(prime-factors 600851475143) ; #{71 839 6857 1471}
(apply max (prime-factors 600851475143)) ; 6857
(defn largests-prime-factor [n]
(apply max (prime-factors n)))
(largests-prime-factor 600851475143) ; 6857
view raw euler-3.clj hosted with ❤ by GitHub

The largests-prime-factor function can be also written in this alternative way using Clojure's ->> macro:

(defn largests-prime-factor [n]
(->>
n
(prime-factors)
(apply max)))
view raw euler-3-b.clj hosted with ❤ by GitHub

No comments:

Post a Comment