testing/collatz.scala
author Christian Urban <urbanc@in.tum.de>
Fri, 10 Nov 2017 09:23:23 +0000
changeset 143 11396c17cd8b
parent 127 b4def82f3f9f
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
//==================================
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     3
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     4
object CW6a {
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
def collatz(n: Long): Long =
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     7
  if (n == 1) 1 else
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     8
    if (n % 2 == 0) 1 + collatz(n / 2) else 
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
     9
      1 + collatz(3 * n + 1)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    10
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    11
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    12
def collatz_max(bnd: Long): (Long, Long) = {
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    13
  val all = for (i <- (1 to bnd.toInt).toList) yield collatz(i)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    14
  val max = all.max
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    15
  (max, all.indexOf(max) + 1)
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    16
}
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    17
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    18
127
b4def82f3f9f updated
Christian Urban <urbanc@in.tum.de>
parents: 126
diff changeset
    19
}
126
c40f364d87eb updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    20