Skip to content

Instantly share code, notes, and snippets.

@mattyw
Created June 8, 2012 08:55
Show Gist options
  • Save mattyw/2894580 to your computer and use it in GitHub Desktop.
Save mattyw/2894580 to your computer and use it in GitHub Desktop.
Project Euler Problem 14 in Clojure
(defn collatz [n]
(if (even? n)
(/ n 2)
(inc (* 3 n))))
(defn collatz-seq [start ls]
(let [next-number (collatz start)]
(if (= start 1)
(conj ls 1)
(collatz-seq next-number (conj ls start)))))
(defn length-of-collatz [start-number]
(count (collatz-seq start-number [])))
(defn collatz-length-map [num end lengths]
(let [collatz-length (length-of-collatz num)]
(if (= num end)
lengths
(recur (inc num) end (assoc lengths collatz-length num)))))
(defn problem16 [start end]
(let [lengths (collatz-length-map start end {})
largest-key (apply max (keys lengths))]
(get lengths largest-key)))
(println (problem16 1 1000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment