progs/live.scala
changeset 10 e7eeeb5b41dc
parent 9 48a477fdef21
child 11 417869f65585
equal deleted inserted replaced
9:48a477fdef21 10:e7eeeb5b41dc
    10   if (n == 1) 1 else
    10   if (n == 1) 1 else
    11     if (n % 2 == 0) (1 + collatz1(n / 2)) else 
    11     if (n % 2 == 0) (1 + collatz1(n / 2)) else 
    12       (1 + collatz1(3 * n + 1))
    12       (1 + collatz1(3 * n + 1))
    13 
    13 
    14 @tailrec
    14 @tailrec
    15 def collatz2(n: BigInt, acc: Int): Int =
    15 def collatz2(n: Long, acc: Int): Int =
    16   if (n == 1) acc else
    16   if (n == 1) acc else
    17     if (n % 2 == 0) collatz2(n / 2, acc + 1) else 
    17     if (n % 2 == 0) collatz2(n / 2, acc + 1) else 
    18       collatz2(3 * n + 1, acc + 1)
    18       collatz2(3 * n + 1, acc + 1)
       
    19 
       
    20 @tailrec
       
    21 def collatz3(n: BigInt, acc: Int): Int =
       
    22   if (n == 1) acc else
       
    23     if (n % 2 == 0) collatz3(n / 2, acc + 1) else 
       
    24       collatz3(3 * n + 1, acc + 1)
    19 
    25 
    20 collatz(1)
    26 collatz(1)
    21 collatz(2)
    27 collatz(2)
    22 collatz(3)
    28 collatz(3)
    23 collatz(4)
    29 collatz(4)
    29 collatz(100000)
    35 collatz(100000)
    30 println((for (i <- 1 to 100000) yield collatz(i).length).max)
    36 println((for (i <- 1 to 100000) yield collatz(i).length).max)
    31 println((for (i <- 1 to 100000) yield collatz1(i)).max)
    37 println((for (i <- 1 to 100000) yield collatz1(i)).max)
    32 println((for (i <- 1 to 1000000) yield collatz2(i, 1)).max)
    38 println((for (i <- 1 to 1000000) yield collatz2(i, 1)).max)
    33 println((for (i <- (1 to 10000000).par) yield collatz2(i, 1)).max)
    39 println((for (i <- (1 to 10000000).par) yield collatz2(i, 1)).max)
    34 println((for (i <- (1 to 100000000).par) yield collatz2(i, 1)).max)
    40 println((for (i <- (1 to 100000000).par) yield collatz3(i, 1)).max)