Tag: factorial

Scala recursive method and tail recursion in factorial

object Functorial {

  def main(args: Array[String]): Unit = {
    println(factorial(3))
    println(factorialWithTailRecursion(3))
  }

  def factorial(n: Int): Int = {
    if (n == 0) 1
    else n * factorial(n - 1)
  }

  def factorialWithTailRecursion(n: Int): Int = {
    def func(acc: Int, n: Int): Int = {
      if (n == 0) acc
      else func(acc * n, n - 1)
    }
    func(1, 3)
  }

}
Advertisements