362
|
1 |
object CW6a {
|
208
|
2 |
|
362
|
3 |
//(1) Complete the collatz function below. It should
|
|
4 |
// recursively calculate the number of steps needed
|
|
5 |
// until the collatz series reaches the number 1.
|
|
6 |
// If needed, you can use an auxiliary function that
|
|
7 |
// performs the recursion. The function should expect
|
|
8 |
// arguments in the range of 1 to 1 Million.
|
208
|
9 |
|
362
|
10 |
def collatz(n: Long) : Long =
|
|
11 |
if ( n == 1) 1;
|
|
12 |
else if (n % 2 == 0) 1 + collatz( n / 2);
|
|
13 |
else 1 + collatz( n * 3 + 1);
|
208
|
14 |
|
|
15 |
|
362
|
16 |
//(2) Complete the collatz_max function below. It should
|
|
17 |
// calculate how many steps are needed for each number
|
|
18 |
// from 1 up to a bound and then calculate the maximum number of
|
|
19 |
// steps and the corresponding number that needs that many
|
|
20 |
// steps. Again, you should expect bounds in the range of 1
|
|
21 |
// up to 1 Million. The first component of the pair is
|
|
22 |
// the maximum number of steps and the second is the
|
|
23 |
// corresponding number.
|
208
|
24 |
|
362
|
25 |
def collatz_max(bnd: Long) : (Long, Long) =
|
|
26 |
((1.toLong to bnd).toList.map
|
|
27 |
(n => collatz(n)).max ,
|
|
28 |
(1.toLong to bnd).toList.map
|
|
29 |
(n => collatz(n)).indexOf((1.toLong to bnd).toList.map
|
|
30 |
(n => collatz(n)).max) + 1);
|
208
|
31 |
|
362
|
32 |
//(3) Implement a function that calculates the last_odd
|
|
33 |
// number in a collatz series. For this implement an
|
|
34 |
// is_pow_of_two function which tests whether a number
|
|
35 |
// is a power of two. The function is_hard calculates
|
|
36 |
// whether 3n + 1 is a power of two. Again you can
|
|
37 |
// assume the input ranges between 1 and 1 Million,
|
|
38 |
// and also assume that the input of last_odd will not
|
|
39 |
// be a power of 2.
|
|
40 |
//idk
|
|
41 |
def is_pow_of_two(n: Long) : Boolean =
|
|
42 |
if ( n & ( n - 1) == 0) true;
|
|
43 |
else false;
|
208
|
44 |
|
362
|
45 |
def is_hard(n: Long) : Boolean =
|
|
46 |
if ( (3*n + 1) & 3*n == 0) true;
|
|
47 |
else false;
|
335
|
48 |
|
|
49 |
|
362
|
50 |
def last_odd(n: Long) : Long = ???
|
335
|
51 |
|
|
52 |
|
|
53 |
|
362
|
54 |
}
|