Project Euler Problem 34

Ivar Thorson bio photo By Ivar Thorson

Ahh, finally a chance to use something I learned shortly after learning it! Problem 34 felt really similar to Problem #30, and the solution even looks similar.

(defn factorial [n] (reduce * (range 2 (inc n))))

(defn curious-num? [n]
  (= n (reduce + (map factorial (as-digits n)))))

(defn euler-34 [search-to]
  (reduce + (filter curious-num? (range 10 search-to))))

(time (euler-34 100000)) ;; "Elapsed time: 4521.082149 msecs"

Now let the optimizations begin! As with problem 30, just caching the values of the expensive computations in a map dramatically improves the speed of things:

(defn euler-34-revised []
  (let [fact (apply hash-map (interleave (seq "0123456789")
                                         (map #(reduce * (range 2 (inc %)))
                                              (range 10))))
        curious? (fn [n] (= n (reduce + (map fact (str n)))))
        max (reduce + (map fact "9999999"))]
    (reduce + (filter curious? (range 10 max)))))

Not surprisingly, since I used the trick I learned earlier from rafsoaken in problem 30, my solution looks and performs similar to the one he posted on clojure-euler.