progs/collatz_sol2.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Thu, 04 Aug 2022 16:53:38 +0200
changeset 426 b51467741af2
parent 50 9891c9fac37e
permissions -rw-r--r--
updated

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

//(1) Complete the collatz function below. It should
//    recursively calculate the number of steps needed 
//    until the collatz series reaches the number 1.
//    If needed you can use an auxilary function that
//    performs the recursion. The function should expect
//    arguments in the range of 1 to 1 Million.

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


// an alternative that calculates the steps directly
def collatz1(n: Long): Long =
  if (n == 1) 1 else
    if (n % 2 == 0) (1 + collatz1(n / 2)) else 
      (1 + collatz1(3 * n + 1))

import scala.annotation.tailrec

@tailrec
def collatz2(n: Long, acc: Long): Long =
  if (n == 1) acc else
    if (n % 2 == 0) collatz2(n / 2, acc + 1) else 
      collatz2(3 * n + 1, acc + 1)


//(2)  Complete the collatz bound function below. It should
//     calculuate how many steps are needed for each number 
//     from 1 upto a bound and return the maximum number of
//     steps and the corresponding number that needs that many 
//     steps. You should expect bounds in the range of 1
//     upto 1 million. 

def collatz_max(bnd: Long): (Long, Long) = {
  (1L to bnd).view.map((i) => (collatz1(i), i)).maxBy(_._1)
}


// some testing harness
//val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 2000000000)



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}")
}


//val all = for (i <- (1 to 100000).toList) yield collatz1(i)
//println(all.sorted.reverse.take(10))