Created
June 8, 2012 08:55
-
-
Save mattyw/2894580 to your computer and use it in GitHub Desktop.
Project Euler Problem 14 in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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