testing1/collatz.scala
author Christian Urban <urbanc@in.tum.de>
Mon, 15 Jan 2018 23:15:34 +0000
changeset 167 349d706586ef
parent 144 716042628398
child 171 4c9497ab5caa
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     1
// Part 1 about the 3n+1 conjecture
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     2
//==================================
167
349d706586ef updated
Christian Urban <urbanc@in.tum.de>
parents: 144
diff changeset
     3
package CW6a 
349d706586ef updated
Christian Urban <urbanc@in.tum.de>
parents: 144
diff changeset
     4
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     5
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     6
object CW6a {
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     7
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     8
def collatz(n: Long): Long =
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     9
  if (n == 1) 1 else
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    10
    if (n % 2 == 0) 1 + collatz(n / 2) else 
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    11
      1 + collatz(3 * n + 1)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    12
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    13
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    14
def collatz_max(bnd: Long): (Long, Long) = {
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    15
  val all = for (i <- (1 to bnd.toInt).toList) yield collatz(i)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    16
  val max = all.max
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    17
  (max, all.indexOf(max) + 1)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    18
}
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    19
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    20
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    21
}
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    22
167
349d706586ef updated
Christian Urban <urbanc@in.tum.de>
parents: 144
diff changeset
    23