| 363 |      1 | // Basic Part about the 3n+1 conjecture
 | 
|  |      2 | //==================================
 | 
|  |      3 | 
 | 
|  |      4 | // generate jar with
 | 
|  |      5 | //   > scala -d collatz.jar  collatz.scala
 | 
|  |      6 | 
 | 
|  |      7 | object CW6a { // for purposes of generating a jar
 | 
| 208 |      8 | 
 | 
| 363 |      9 | /*
 | 
|  |     10 | def collatz(n: Long): Long =
 | 
|  |     11 |   if (n == 1) 0 else
 | 
|  |     12 |     if (n % 2 == 0) 1 + collatz(n / 2) else 
 | 
|  |     13 |       1 + collatz(3 * n + 1)
 | 
|  |     14 | */
 | 
| 208 |     15 | 
 | 
| 363 |     16 | def aux(n: Long, acc: Long) : Long =
 | 
|  |     17 |   if (n == 1) acc else
 | 
|  |     18 |     if (n % 2 == 0) aux(n / 2, acc + 1) else
 | 
|  |     19 |       aux(3 * n + 1, acc + 1)
 | 
| 208 |     20 | 
 | 
|  |     21 | 
 | 
| 363 |     22 | def collatz(n: Long): Long = aux(n, 0)
 | 
|  |     23 | 
 | 
|  |     24 | def collatz_max(bnd: Long): (Long, Long) = {
 | 
|  |     25 |   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
 | 
|  |     26 |   all.maxBy(_._1)
 | 
|  |     27 | }
 | 
| 208 |     28 | 
 | 
| 363 |     29 | //collatz_max(1000000)
 | 
|  |     30 | //collatz_max(10000000)
 | 
|  |     31 | //collatz_max(100000000)
 | 
|  |     32 | 
 | 
|  |     33 | /* some test cases
 | 
|  |     34 | val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
 | 
| 208 |     35 | 
 | 
| 363 |     36 | for (bnd <- bnds) {
 | 
|  |     37 |   val (steps, max) = collatz_max(bnd)
 | 
|  |     38 |   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
 | 
|  |     39 | }
 | 
|  |     40 | 
 | 
|  |     41 | */
 | 
| 208 |     42 | 
 | 
| 363 |     43 | def is_pow(n: Long) : Boolean = (n & (n - 1)) == 0
 | 
|  |     44 | 
 | 
|  |     45 | def is_hard(n: Long) : Boolean = is_pow(3 * n + 1)
 | 
|  |     46 | 
 | 
|  |     47 | def last_odd(n: Long) : Long = 
 | 
|  |     48 |   if (is_hard(n)) n else
 | 
|  |     49 |     if (n % 2 == 0) last_odd(n / 2) else 
 | 
|  |     50 |       last_odd(3 * n + 1)
 | 
| 335 |     51 | 
 | 
|  |     52 | 
 | 
| 363 |     53 | //for (i <- 130 to 10000) println(s"$i: ${last_odd(i)}")
 | 
|  |     54 | //for (i <- 1 to 100) println(s"$i: ${collatz(i)}")
 | 
|  |     55 | 
 | 
|  |     56 | }
 | 
| 335 |     57 | 
 | 
|  |     58 | 
 | 
|  |     59 | 
 |