Created
August 16, 2021 09:46
-
-
Save oswaldo/c3ee1ac25f9e945275a595e6859d0f02 to your computer and use it in GitHub Desktop.
Simple Collatz sequence implementation
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
//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