equal
deleted
inserted
replaced
1 import scala.annotation.tailrec |
|
2 |
|
3 |
|
4 def collatz(n: Long): List[Long] = |
|
5 if (n == 1) List(1) else |
|
6 if (n % 2 == 0) (n::collatz(n / 2)) else |
|
7 (n::collatz(3 * n + 1)) |
|
8 |
|
9 def collatz1(n: Long): Int = |
|
10 if (n == 1) 1 else |
|
11 if (n % 2 == 0) (1 + collatz1(n / 2)) else |
|
12 (1 + collatz1(3 * n + 1)) |
|
13 |
|
14 @tailrec |
|
15 def collatz2(n: Long, acc: Int): Int = |
|
16 if (n == 1) acc else |
|
17 if (n % 2 == 0) collatz2(n / 2, acc + 1) else |
|
18 collatz2(3 * n + 1, acc + 1) |
|
19 |
|
20 collatz(1) |
|
21 collatz(2) |
|
22 collatz(3) |
|
23 collatz(4) |
|
24 collatz(5) |
|
25 collatz(6).length |
|
26 collatz(7) |
|
27 collatz(8) |
|
28 collatz(9).length |
|
29 collatz(100000) |
|
30 println((for (i <- 1 to 10000000) yield collatz(i).length).max) |
|
31 println((for (i <- 1 to 10000000) yield collatz1(i)).max) |
|
32 println((for (i <- 1 to 10000000) yield collatz2(i, 1)).max) |
|
33 println((for (i <- (1 to 10000000).par) yield collatz2(i, 1)).max) |
|
34 |
|