Created
March 9, 2010 14:57
-
-
Save leedm777/326665 to your computer and use it in GitHub Desktop.
Collatz algorithm in Scala and 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 | |
#^{:doc "Clojure code to compute a Collatz sequence."} | |
collatz [n] | |
(if (= n 1) | |
'(1) | |
(cons n | |
(collatz (if (= (mod n 2) 0) | |
(/ n 2) | |
(+ (* n 3) 1)))))) |
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
/** | |
* Scala code to compute a Collatz sequence. | |
* See http://en.wikipedia.org/wiki/Collatz_conjecture | |
*/ | |
def collatz(n:BigInt):Stream[BigInt] = | |
if (n == 1) { | |
Stream(1); | |
} else { | |
def next(n:BigInt):BigInt = if ((n % 2) == 0) (n / 2) else (n * 3 + 1); | |
Stream.cons(n, collatz(next(n))); | |
} |
rferrerme
commented
Aug 9, 2016
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment