Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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))
share|improve this question
1  
I wouldn't call this code optimized. If you want the fastest possible run time for Euler #14, you need to realize that there's a way to use more memory in exchange for much shorter execution time. – WolfeFan Feb 16 at 23:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.