core_testing1/collatz.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Sat, 11 Mar 2023 22:01:53 +0000
changeset 463 0315d9983cd0
parent 433 6af86ba1208f
child 472 6a77c260c8a5
permissions -rw-r--r--
updated

import scala.annotation.tailrec
// Core Part 1 about the 3n+1 conjecture
//============================================

object C1 {

@tailrec
private def collatz(n: Long, steps: Long = 0): Long = {
  if (n == 1) steps
  else if (n % 2 == 0) collatz(n / 2, steps + 1)
  else collatz(n * 3 + 1, steps + 1)
}

def collatz_max(upper: Long): (Long, Long) = {
  (1L to upper).map(n => (collatz(n), n)).maxBy(_._1)
}


private def is_pow_of_two(n: Long) : Boolean = {
  (n & (n - 1)) == 0
}

private def is_hard(n: Long) : Boolean = {
  is_pow_of_two(3 * n + 1)
}


private def last_odd(n: Long): Long = {
  (1L to n).filter(is_hard).max
}

}



// This template code is subject to copyright 
// by King's College London, 2022. Do not 
// make the template code public in any shape 
// or form, and do not exchange it with other 
// students under any circumstance.