282
|
1 |
// Basic Part about the 3n+1 conjecture
|
208
|
2 |
//==================================
|
|
3 |
|
266
|
4 |
// generate jar with
|
|
5 |
// > scala -d collatz.jar collatz.scala
|
208
|
6 |
|
|
7 |
object CW6a { // for purposes of generating a jar
|
|
8 |
|
|
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)
|
|
13 |
|
|
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 |
}
|
|
19 |
|
320
|
20 |
//collatz_max(1000000)
|
|
21 |
//collatz_max(10000000)
|
|
22 |
//collatz_max(100000000)
|
208
|
23 |
|
|
24 |
/* some test cases
|
|
25 |
val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
|
|
26 |
|
|
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 |
*/
|
|
33 |
|
335
|
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)
|
|
42 |
|
|
43 |
|
336
|
44 |
//for (i <- 130 to 10000) println(s"$i: ${last_odd(i)}")
|
|
45 |
for (i <- 1 to 100) println(s"$i: ${collatz(i)}")
|
335
|
46 |
|
208
|
47 |
}
|
335
|
48 |
|
|
49 |
|
|
50 |
|