diff -r 34feeb53c0ba -r 0315d9983cd0 core_testing1/collatz.scala --- a/core_testing1/collatz.scala Sun Jan 15 10:58:13 2023 +0000 +++ b/core_testing1/collatz.scala Sat Mar 11 22:01:53 2023 +0000 @@ -1,46 +1,33 @@ +import scala.annotation.tailrec // Core Part 1 about the 3n+1 conjecture //============================================ object C1 { -// ADD YOUR CODE BELOW -//====================== - -// test1 7 Nov -// test2 -// test3 -// test4 - +@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) +} -//(1) -def collatz(n: Long) : Long = - if (n == 1) 0 else - if (n % 2 == 0) 1 + collatz(n / 2) else - 1 + collatz(3 * n + 1) - - -//(2) -//def collatz_max(bnd: Long) : (Long, Long) = { -// val all = for (i <- (1L to bnd)) yield (collatz(i), i) -// all.maxBy(_._1) -//} - -def collatz_max(bnd: Long): (Long, Long) = { - val all = for (i <- (1L to bnd)) yield (collatz(i), i) - all.maxBy(_._1) +def collatz_max(upper: Long): (Long, Long) = { + (1L to upper).map(n => (collatz(n), n)).maxBy(_._1) } - -//(3) - -def is_pow_of_two(n: Long) : Boolean = (n & (n - 1)) == 0 +private def is_pow_of_two(n: Long) : Boolean = { + (n & (n - 1)) == 0 +} -def is_hard(n: Long) : Boolean = is_pow_of_two(3 * n + 1) +private def is_hard(n: Long) : Boolean = { + is_pow_of_two(3 * n + 1) +} -def last_odd(n: Long) : Long = if (is_hard(n)) n else - if (n % 2 == 0) last_odd(n / 2) else - last_odd(3 * n + 1) + +private def last_odd(n: Long): Long = { + (1L to n).filter(is_hard).max +} }