Problem 14 on project Euler is to find the number under 1,000,000 that is the start of the longest Collatz sequence. My solution is below, basically it uses a hash map to cache the lengths of collatz sequences. But when I get to 113383 the collatz function just bounces between the numbers 1, 2, and 4. Those numbers seem to be in the map but contains? just keeps returning false.
(ns euler.problem14) (def lengths (atom {1 0})) (defn collatz [input] (loop [current input accum 0] (when (= input 113383) (println current accum (filter #(< % 10) (keys @lengths)))) (if (contains? @lengths current) (do (swap! lengths #(assoc % input (+ accum (get % current)))) (get @lengths input)) (if (zero? (mod current 2)) (recur (/ current 2) (inc accum)) (recur (inc (* 3 current)) (inc accum)))))) (time (println (last (sort-by #(second %) (for [x (range 1 1000000)] (do (println x) [x (collatz x)])))))) -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en