Created
February 1, 2013 02:26
-
-
Save zmaril/4688693 to your computer and use it in GitHub Desktop.
Collatz fun
This file contains 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
(ns collatz.core) | |
(defn collatz | |
"Given n, it returns n/2 if it's even or n*3+1 if it's odd." | |
[n] | |
(if (even? n) | |
(/ n 2) | |
(+ (* 3 n) 1))) | |
(declare count-steps-of-collatz) | |
(def count-small-steps-of-collatz | |
(memoize | |
(fn [n] | |
(if (= n 1) 0 | |
(inc (count-small-steps-of-collatz (collatz n))))))) | |
(def count-large-steps-of-collatz | |
(fn [n] | |
(if (= n 1) 0 | |
(inc (count-steps-of-collatz (collatz n)))))) | |
(defn count-steps-of-collatz [n] | |
(if (< n 100000) | |
(count-small-steps-of-collatz n) | |
(count-large-steps-of-collatz n))) | |
(defn integer-below-n-with-most-steps [n] | |
(->> (pmap (juxt identity count-steps-of-collatz) (range 1 n)) | |
(apply (partial max-key second)))) | |
(defn -main [] | |
(doseq [i (take 7 (iterate (partial * 10) 10))] | |
(time (println (integer-below-n-with-most-steps i)))) | |
(System/exit 0)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment