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
(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 |
The largests-prime-factor function can be also written in this alternative way using Clojure's ->> macro:
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 largests-prime-factor [n] | |
(->> | |
n | |
(prime-factors) | |
(apply max))) |
No comments:
Post a Comment