Skip to content

Instantly share code, notes, and snippets.

@pmbauer
Created August 22, 2011 03:14
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 pmbauer/1161579 to your computer and use it in GitHub Desktop.
Save pmbauer/1161579 to your computer and use it in GitHub Desktop.
Three Clojure solutions to Euler 14
(ns euler14
(:use [clojure.repl]))
(defn max-euler14 [count-fn upper-bound]
(->> (range 1 (inc upper-bound))
(map (juxt identity count-fn))
(reduce (partial max-key second))))
; idiomatic
(defn euler14-terms [n]
(lazy-seq
(if (= n 1)
[1]
(cons n (euler14-terms (if (even? n)
(/ n 2)
(inc (* 3 n))))))))
; note that euler14-terms, range, and map are all lazy, and don't hang onto
; the list head, so auxiliary memory overhead is constant
(comment
(time
(max-euler14 (comp count euler14-terms) 1000000)))
; faster
(defn euler14-terms-count [n]
(loop [n n terms 1]
(if (= n 1)
terms
(recur (if (even? n) (/ n 2) (inc (* 3 n)))
(inc terms)))))
(comment
(time
(max-euler14 euler14-terms-count 1000000)))
; fastest (memoized)
(declare euler14-terms-count-memoized)
(defn euler14-terms-count* [n]
(if (= n 1)
1
(inc (euler14-terms-count-memoized
(if (even? n) (/ n 2) (inc (* 3 n)))))))
(def euler14-terms-count-memoized (memoize euler14-terms-count*))
(comment
(time
(max-euler14 euler14-terms-count-memoized 1000000)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment