Project Euler Problem 65

Ivar Thorson bio photo By Ivar Thorson

Problem 65 continues our exploration of continued fractions, although this time a different property is the focus: the ability to generate rational fractions that converge on better and better approximations to the number e.

This problem was a rather straightforward to implement.

(defn as-digits [num]  (map #(Character/getNumericValue %) (str num)))

(def continued-fraction-of-e (cons 2 (interleave (repeat 1)
                                                 (map #(* 2 (inc %)) (range))
                                                 (repeat 1))))

(defn convergents [coll]
  (let [f (fn [[as h1 h2]] [(next as) (+ (* (first as) h1) h2) h1])
        hs (rest (map second (iterate f [coll 1 0])))
        ks (rest (map second (iterate f [coll 0 1])))]
    (map / hs ks)))

(defn euler-65 []
  (->> (nth (convergents continued-fraction-of-e) (dec 100))
       (numerator)
       (as-digits)
       (reduce +)))

(time (euler-65)) ;; "Elapsed time: 5.171186 msecs"

Just for kicks, I used the -» operator in euler-65 to show the sequential nature of the last little calculation. Lately I have been thinking about how all my programs run inside out, so returning to a “list of operations” style of programming somehow feels a little novel.