testing1/collatz.scala
changeset 281 87b9e3e2c1a7
parent 199 54befaf23648
child 314 21b52310bd8b
equal deleted inserted replaced
280:a057dc4457fc 281:87b9e3e2c1a7
     1 // Part 1 about the 3n+1 conjecture
     1 // Part 1 about the 3n+1 conjecture
     2 //==================================
     2 //==================================
     3 
     3 
       
     4 // generate jar with
       
     5 //   > scala -d collatz.jar  collatz.scala
     4 
     6 
     5 //object CW6a { // for purposes of generating a jar
     7 object CW6a { 
       
     8 
     6 
     9 
     7 def collatz(n: Long): Long =
    10 def collatz(n: Long): Long =
     8   if (n == 1) 0 else
    11   if (n == 1) 0 else
     9     if (n % 2 == 0) 1 + collatz(n / 2) else 
    12     if (n % 2 == 0) 1 + collatz(n / 2) else 
    10       1 + collatz(3 * n + 1)
    13       1 + collatz(3 * n + 1)
    13 def collatz_max(bnd: Long): (Long, Long) = {
    16 def collatz_max(bnd: Long): (Long, Long) = {
    14   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
    17   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
    15   all.maxBy(_._1)
    18   all.maxBy(_._1)
    16 }
    19 }
    17 
    20 
       
    21 
    18 /* some test cases
    22 /* some test cases
    19 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    23 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    20 
    24 
    21 for (bnd <- bnds) {
    25 for (bnd <- bnds) {
    22   val (steps, max) = collatz_max(bnd)
    26   val (steps, max) = collatz_max(bnd)
    23   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    27   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    24 }
    28 }
    25 
    29 
    26 */
    30 */
    27 
    31 
    28 //}
    32 
       
    33 }
       
    34 
       
    35 
       
    36