Project Euler Problem 57

Ivar Thorson bio photo By Ivar Thorson

Project Euler Problem 57 was a little too easy, not even taking 15 minutes to write and test. Even then, I spent the majority of my time staring at the recursive form of the expansion of sqrt(2) until I saw how to write it as an infinite sequence. (A pen and paper may help you figure it out.)

(def sqrt2-approx (iterate #(/ (+ (numerator %) (* 2 (denominator %)))
                               (+ (numerator %) (denominator %)))
                           (/ 3 2)))

(defn bigger-numerator? [n]
  (> (count (str (numerator n)))
     (count (str (denominator n)))))

(defn euler-57 []
  (count (filter bigger-numerator? (take 1000 sqrt2-approx))))

(time (euler-57)) ;; "Elapsed time: 144.948143 msecs"

Using Clojure’s fractional types here lets us avoid some of the syntactic noise that using separate denominator and numerator fields, multiple return arguments, destructuring the arguments would require.