progs/collatz_sol.scala
changeset 24 66b97f9a40f8
parent 18 87e55eb309ed
child 64 d6f97b562424
equal deleted inserted replaced
23:8ac886bb0c15 24:66b97f9a40f8
     4 //(1) Complete the collatz function below. It should
     4 //(1) Complete the collatz function below. It should
     5 //    recursively calculate the number of steps needed 
     5 //    recursively calculate the number of steps needed 
     6 //    until the collatz series reaches the number 1.
     6 //    until the collatz series reaches the number 1.
     7 //    If needed you can use an auxilary function that
     7 //    If needed you can use an auxilary function that
     8 //    performs the recursion. The function should expect
     8 //    performs the recursion. The function should expect
     9 //    arguments in the range of 1 to 10 Million.
     9 //    arguments in the range of 1 to 1 Million.
    10 
    10 
    11 def collatz(n: Long): List[Long] =
    11 def collatz(n: Long): List[Long] =
    12   if (n == 1) List(1) else
    12   if (n == 1) List(1) else
    13     if (n % 2 == 0) (n::collatz(n / 2)) else 
    13     if (n % 2 == 0) (n::collatz(n / 2)) else 
    14       (n::collatz(3 * n + 1))
    14       (n::collatz(3 * n + 1))