Friday, March 5, 2010

Collatz

After seeing the xkcd on the Collatz Conjecture, I had to write an example in Scala.
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)));
}
That was a fun little diversion!