Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program to find Factorial of a given number using Tail Recursion.
Tail Recursion: If a function calls itself as the last action in the definition, it is called as Tail Recursion.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.clearurdoubt object Factorial extends App { def factorial(n: Int) : Int = { def factorial(n: Int, returnValue: Int) : Int = { if (n == 0) returnValue else factorial(n-1, n * returnValue) // Tail Recursion } factorial(n, 1) } println(factorial(10)) } |
Output:
In case of Tail Recursive calls, Scala compiler will try to optimize the recursive calls using single stack frame whereas in case of Linear Recursive calls multiple stack frames are used.
Happy Learning.
Please leave a reply in case of any queries.