Here is the problem:
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
I have some serious misgivings about how good/idiomatic my Clojure code is. I have a very Haskell-ish implementation that runs very slowly, that I'm happy with, but this optimized version seems really clunky to me, although it runs ~20x faster.
(ns project-euler.fast-problem14)
;; I've decided to stop posting the slow versions of these. Their effectivly useless at this point except for me showing off.
(defn chain-step [n]
(cond
(even? n) (/ n 2)
(odd? n) (inc (* 3 n))))
(defn fast-chain-length [n]
(if-not (zero? n)
(loop [n n, c 1]
(let [step (chain-step n)]
(if (= step 1)
(inc c)
(recur step (inc c)))))
0))
(defn fast-problem14 [start]
(loop [n (dec start), max-len 0, max-n (dec start)]
(if-not (zero? n)
(let [len (fast-chain-length n)]
(if (> len max-len)
(recur (dec n) len n)
(recur (dec n) max-len max-n)))
max-n)))
(defn run-problem [] (fast-problem14 1000000))