Skip to content

Instantly share code, notes, and snippets.

@oswaldo
Created August 16, 2021 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oswaldo/c3ee1ac25f9e945275a595e6859d0f02 to your computer and use it in GitHub Desktop.
Save oswaldo/c3ee1ac25f9e945275a595e6859d0f02 to your computer and use it in GitHub Desktop.
Simple Collatz sequence implementation
//scala3 version in https://scastie.scala-lang.org/oswaldo/D18phCIFTzuH14BHLxKTNA/6
object Collatz extends App {
val stop = BigInt(1)
def sequence(n: BigInt): Stream[BigInt] = Stream(n) #::: {
n match {
case `stop` =>
println(s"$n, stopping")
Stream.empty[BigInt]
case step => sequence(if (n % 2 == 0) {
println(s"$n is even\n => $n / 2")
n / 2
} else {
println(s"$n is odd\n => 3 * $n + 1")
3 * n + 1
}
)
}
}
val n = BigInt(42)
//val n = BigDecimal("1e100").toBigInt
val s = sequence(n)
println(s"Collatz for $n:\n\n")
println("\nsequence: " + s.mkString(", "))
println("size: " + s.size)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment