progs/collatz.scala
changeset 15 52713e632ac0
parent 11 417869f65585
child 18 87e55eb309ed
equal deleted inserted replaced
14:2d9defa8ad7f 15:52713e632ac0
     1 // Part 1
     1 // Part 1 about the 3n+1 conceture
       
     2 //=================================
     2 
     3 
     3 
     4 
     4 //(1)
     5 //(1) Complete the collatz function below. It should
     5 def collatz(n: Long): List[Long] =
     6 //    recursively calculate the number of steps needed 
     6   if (n == 1) List(1) else
     7 //    until the collatz series reaches the number 1.
     7     if (n % 2 == 0) (n::collatz(n / 2)) else 
     8 //    If needed you can use an auxilary function that
     8       (n::collatz(3 * n + 1))
     9 //    performs the recursion. The function should expect
       
    10 //    arguments in the range of 1 to 10 Million.
     9 
    11 
    10 // an alternative that calculates the steps directly
    12 def collatz(n: Long): Int = ...
    11 def collatz1(n: Long): Int =
       
    12   if (n == 1) 1 else
       
    13     if (n % 2 == 0) (1 + collatz1(n / 2)) else 
       
    14       (1 + collatz1(3 * n + 1))
       
    15 
    13 
    16 
    14 
    17 //(2)
    15 //(2)  Complete the collatz bound function below. It should
    18 def collatz_max(bnd: Int): Int = {
    16 //     calculuate how many steps are needed for each number 
    19   (for (i <- 1 to bnd) yield collatz(i).length).max
    17 //     from 1 upto a bound and return the maximum number of
    20 }
    18 //     steps. You should expect bounds in the range of 1
       
    19 //     upto 10 million. 
       
    20 
       
    21 def collatz_max(bnd: Int): Int = ...
    21 
    22 
    22 
    23 
    23 val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000)
       
    24 
       
    25 for (bnd <- bnds) {
       
    26   val max = collatz_max(bnd)
       
    27   println(s"In the range of 1 - ${bnd} the maximum steps are ${max}")
       
    28 }
       
    29