In Pascal's Triangle the number at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. A sample Pascal's triangle would look like below.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
I wrote a program that computes the elements of Pascal's triangle using below technique.
/**
* Can I make it tail recursive???
*
* @param c column
* @param r row
* @return
*/
def pascalTriangle(c: Int, r: Int): Int = {
if (c == 0 || (c == r)) 1
else
pascalTriangle(c-1, r-1) + pascalTriangle(c, r - 1)
}
So, for example if
i/p: pascalTriangle(0,2)
o/p: 1.
i/p: pascalTriangle(1,3)
o/p: 3.
Above program is correct and giving the correct output as expected. My question is, is it possible to write tail recursive version of above algorithm? How?