3 Banana Monkey

Factorial

January 1, 2016

Iterative

def factorial(n: Int): Long = {
   var result = 1L
   if (n <= 1) {
      result
   } else {
      for (i <- 2 to n) {
         result = result * i
      }
      result
   }
}

Recursive

def factorial(n: Long): Long = {
   if (n <= 1) {
      1L
   } else {
      n * factorial(n - 1)
   }
}

Tail Recursive

def factorial(n: Int): Long = {
   factorial(n - 1, n)
}
 
def factorial(n: Long, accumulator: Long): Long = {
   if (n <= 1) {
      accumulator
   } else {
      factorial(n - 1, n * accumulator)
   }
}