progs/collatz_.scala
changeset 16 714e60f22b17
parent 15 52713e632ac0
child 17 ecf83084e41d
equal deleted inserted replaced
15:52713e632ac0 16:714e60f22b17
     1 // Part 1
       
     2 
       
     3 
       
     4 //(1)
       
     5 def collatz(n: Long): List[Long] =
       
     6   if (n == 1) List(1) else
       
     7     if (n % 2 == 0) (n::collatz(n / 2)) else 
       
     8       (n::collatz(3 * n + 1))
       
     9 
       
    10 // an alternative that calculates the steps directly
       
    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 
       
    16 
       
    17 //(2)
       
    18 def collatz_max(bnd: Int): Int = {
       
    19   (for (i <- 1 to bnd) yield collatz(i).length).max
       
    20 }
       
    21 
       
    22 
       
    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