--- a/core_testing1/collatz.scala Wed Nov 01 15:01:32 2023 +0000
+++ b/core_testing1/collatz.scala Thu Nov 02 11:32:10 2023 +0000
@@ -1,33 +1,27 @@
-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)
-}
+def collatz(n: Long): Long =
+ if (n == 1) 0 else
+ if (n % 2 == 0) 1 + collatz(n / 2) else
+ 1 + collatz(3 * n + 1)
-private def is_pow_of_two(n: Long) : Boolean = {
- (n & (n - 1)) == 0
+def collatz_max(bnd: Long): (Long, Long) = {
+ val all = for (i <- (1L to bnd)) yield (collatz(i), i)
+ all.maxBy(_._1)
}
-private def is_hard(n: Long) : Boolean = {
- is_pow_of_two(3 * n + 1)
-}
+def is_pow(n: Long) : Boolean = (n & (n - 1)) == 0
+
+def is_hard(n: Long) : Boolean = is_pow(3 * n + 1)
-
-private def last_odd(n: Long): Long = {
- (1L to n).filter(is_hard).max
-}
+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)
}