Skip to content

Instantly share code, notes, and snippets.

@ziotom78
Created September 28, 2011 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziotom78/1247543 to your computer and use it in GitHub Desktop.
Save ziotom78/1247543 to your computer and use it in GitHub Desktop.
Solution for Project Euler's problem 34 (Clojure)
(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