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