Created
September 28, 2011 10:05
-
-
Save ziotom78/1247543 to your computer and use it in GitHub Desktop.
Solution for Project Euler's problem 34 (Clojure)
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 fact | |
"Return n!." | |
[^Integer n] | |
(if (< n 2) | |
1 | |
(apply * (range 2 (+ n 1))))) | |
(def fast-fact | |
; This is a faster version of "fact", using a dictionary to return the | |
; factorial for any number between 0 and 9 (the only kind of number for which | |
; we want the factorial here). | |
(reduce (fn [dict n] (assoc dict n (fact n))) {} (range 0 10))) | |
(defn digits | |
"Return a list of the digits of n." | |
[^Integer n] | |
(map #(- (int %) 48) (.toString n))) | |
(defn test-number | |
"Check if n is equal to the factorials of its digits." | |
[^Integer n] | |
(let [factorials fast-fact] | |
(= n (apply + (map fast-fact (digits n)))))) | |
(defn solution | |
"Return the solution for the problem." | |
[^Integer max-n] | |
(apply + (filter test-number (range 10 max-n)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment