progs/collatz_sol.scala
changeset 15 52713e632ac0
parent 11 417869f65585
child 17 ecf83084e41d
equal deleted inserted replaced
14:2d9defa8ad7f 15:52713e632ac0
       
     1 // Part 1 about the 3n+1 conceture
       
     2 //=================================
       
     3 
       
     4 
       
     5 //(1) Complete the collatz function below. It should
       
     6 //recursively calculates the number of steps needed 
       
     7 //number until a series ends with 1
       
     8 
       
     9 def collatz(n: Long): List[Long] = ...
       
    10 
       
    11 
       
    12 // an alternative that calculates the steps directly
       
    13 def collatz1(n: Long): Int =
       
    14   if (n == 1) 1 else
       
    15     if (n % 2 == 0) (1 + collatz1(n / 2)) else 
       
    16       (1 + collatz1(3 * n + 1))
       
    17 
       
    18 
       
    19 //(2)
       
    20 def collatz_max(bnd: Int): Int = {
       
    21   (for (i <- 1 to bnd) yield collatz(i).length).max
       
    22 }
       
    23 
       
    24 
       
    25 val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000)
       
    26 
       
    27 for (bnd <- bnds) {
       
    28   val max = collatz_max(bnd)
       
    29   println(s"In the range of 1 - ${bnd} the maximum steps are ${max}")
       
    30 }
       
    31