Skip to content

Instantly share code, notes, and snippets.

@leedm777
Created March 9, 2010 14:57
Show Gist options
  • Save leedm777/326665 to your computer and use it in GitHub Desktop.
Save leedm777/326665 to your computer and use it in GitHub Desktop.
Collatz algorithm in Scala and Clojure
(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))))))
/**
* 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
Copy link

rferrerme commented Aug 9, 2016

/**
 * Using match.
 */

import scala.math.BigInt

def collatz(number: BigInt): Stream[BigInt] = number match {
  case n if n == 1 => Stream(1)
  case n if n % 2 == 0 => Stream.cons(number, collatz(number / 2))
  case _ => Stream.cons(number, collatz(number * 3 + 1))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment