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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s