core_testing1/collatz.scala
changeset 401 9471c3b7ea02
parent 399 b17a98b0c52f
child 433 6af86ba1208f
equal deleted inserted replaced
400:e48ea8300b2d 401:9471c3b7ea02
     1 // Basic Part about the 3n+1 conjecture
     1 // Core Part 1 about the 3n+1 conjecture
     2 //==================================
     2 //==================================
     3 
     3 
     4 // generate jar with
     4 // generate jar with
     5 //   > scala -d collatz.jar  collatz.scala
     5 //   > scala -d collatz.jar  collatz.scala
     6 
     6 
    16   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
    16   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
    17   all.maxBy(_._1)
    17   all.maxBy(_._1)
    18 }
    18 }
    19 
    19 
    20 //collatz_max(1000000)
    20 //collatz_max(1000000)
    21 //collatz_max(10000000)
    21 
    22 //collatz_max(100000000)
       
    23 
    22 
    24 /* some test cases
    23 /* some test cases
    25 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    24 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    26 
    25 
    27 for (bnd <- bnds) {
    26 for (bnd <- bnds) {
    29   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    28   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    30 }
    29 }
    31 
    30 
    32 */
    31 */
    33 
    32 
       
    33 
    34 def is_pow(n: Long) : Boolean = (n & (n - 1)) == 0
    34 def is_pow(n: Long) : Boolean = (n & (n - 1)) == 0
    35 
    35 
    36 def is_hard(n: Long) : Boolean = is_pow(3 * n + 1)
    36 def is_hard(n: Long) : Boolean = is_pow(3 * n + 1)
    37 
    37 
    38 def last_odd(n: Long) : Long = 
    38 def last_odd(n: Long) : Long = 
    39   if (is_hard(n)) n else
    39   if (is_hard(n)) n else
    40     if (n % 2 == 0) last_odd(n / 2) else 
    40     if (n % 2 == 0) last_odd(n / 2) else 
    41       last_odd(3 * n + 1)
    41       last_odd(3 * n + 1)
    42 
    42 
    43 
    43 
       
    44 
    44 //for (i <- 130 to 10000) println(s"$i: ${last_odd(i)}")
    45 //for (i <- 130 to 10000) println(s"$i: ${last_odd(i)}")
    45 //for (i <- 1 to 100) println(s"$i: ${collatz(i)}")
    46 //for (i <- 1 to 100) println(s"$i: ${collatz(i)}")
    46 
    47 
    47 }
    48 }
    48 
    49