Project Euler Problem 55

Ivar Thorson bio photo By Ivar Thorson

For problem 55, we need to count the number of Lychrel numbers below ten thousand. I almost tagged this as too-easy, but I spent about 20 minutes figuring out why my four line solution wasn’t correct (hint: you shouldn’t check if the Lychrel number itself is palendromic).

(defn palindromic? [n]
  (= (seq (str n)) (reverse (str n))))

(defn next-lychrel [n]
  (+ n (BigInteger. (apply str (reverse (str n))))))

(defn lychrel? [n] 
  {:pre [(< n 10000)]} ;; only numbers < 10000 converge in <50 iterations
  (not-any? palindromic? (take 50 (rest (iterate next-lychrel n)))))

(defn euler-55 []
  (count (filter lychrel? (range 1 10000))))

(time (euler-55)) ;; "Elapsed time: 377.757553 msecs"

Performance seems adequate. See you tomorrow!