testing1/collatz.scala
author Christian Urban <urbanc@in.tum.de>
Wed, 06 Nov 2019 00:36:45 +0000
changeset 314 21b52310bd8b
parent 281 87b9e3e2c1a7
child 320 cdfb2ce30a3d
permissions -rw-r--r--
updated

// Part 1 about the 3n+1 conjecture
//==================================

// generate jar with
//   > scala -d collatz.jar  collatz.scala

object CW6a { 


/*
 * def collatz(n: Long): Long =
  if (n == 1) 0 else
    if (n % 2 == 0) 1 + collatz(n / 2) else 
      1 + collatz(3 * n + 1)
*/

def collatz_max(bnd: Long): (Long, Long) = {
  val all = for (i <- (1L to bnd)) yield (collatz(i), i)
  all.maxBy(_._1)
}


/* some test cases
val bnds = List(10, 100, 1000, 10000, 100000, 1000000)

for (bnd <- bnds) {
  val (steps, max) = collatz_max(bnd)
  println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
}

*/




def collatz(n: Long) : Long = {
    if (n == 1) {
        1L
    } else {
        if (n % 2 == 0) {
            collatz(n/2) + 1
        } else {
            collatz((n*3)+1) + 1
        }
    }
}

}