Challenge: Tail Recursion
Test yourself and implement what you have learned so far in this challenge.
We'll cover the following
Problem Statement
In a previous lesson on recursion, we implemented the recursive factorial function. You need to design a tail-recursive version of the factorial function given below.
def factorial(x: Int) : Int = {if(x == 1)1elsex * factorial(x-1)}// Driver Codeprint(factorial(3))
The tail recursive version of factorial requires a nested function
loop
.loop
has two parameters:accumulator
andx
and is the tail recursive part of factorial. All you have to do is figure out what the function body ofloop
should contain.
Input
The input of the function is a number x
of type Int
whose factorial value you want to compute.
Output
The output will be the factorial of x
.
Sample Input
5
Sample Output
120
Test Yourself
Write your code in the given area. Try the exercise by yourself first, but if you get stuck, the solution has been provided. Good luck!
def factorial(x: Int): Int = {def loop(accumulator: Int, x: Int): Int = {// Write your code herereturn -1 // Remove this line after writing your code}loop(1,x)}
Let’s go over the solution review in the next lesson.