Tail Recursion 1
Tail Recursion 1
18, 12 main()
gcd (12, 6)
6, 0 30, 18
gcd (18, 12)
param x
12, 6
gcd (30, 18)
m;return gcd(n,
int gcd(int m, m%n); }
int n){
if(n==0) return x = gcd(30,18)
R1 = 6
main () - Stack
frame for Caller
gcd-IV - gcd (6,0)
Caller
gcd-I - gcd (12, 6) Caller
R1 = 6
main () - Stack frame for gcd-I - gcd (6,0)
Stack frame poped out for every call and the same space is
reallocated for a frame of the next recursive call
• int fact(unsigned int n) {
• Can we convert a recursive function to a
Recursive to Tail-Recursive Function
• Can be done using a jacket function for
• Tail Recursive Function
• Non-tail Recursive Function
• int factorial (int n) { return fac (n,1) }
if (n == 0) return 1; return int fac(int n, int a) {
n*fact(n-1); }
• The function is not tail-recursive because
if (n==0) return a;
the value returned by fact(n-1) is used in
return fac(n-1, n*a);
fact(n) and call to fact(n-1) is not the last
}
thing done by fact(n). • what is use of 'a'? - 'a' (accumlator)
would be an extra parameter used for
tail-recursive function? every recursive
the purpose of storing the partial
results.
call/function.
returning from a recursive call by passing that work into the recursive call, in the
form of a continuation.
Approach-I: Using Tree Recursion int fib
(int n)
Ex. fib(100)
{ How many times fib (95)
fib(5)
may have to
fib(4) fib(3)
if (n==0) fib(2) fib
be calculated?
fib(1) fib
return 0; else
else if (n==1) return -Exponential
1; return (fib(n-1),
fib(3) fib(2) fib(2) fib(1) fib(n-2))
Complexity?
(1) Iterative version - o(n)
(linear)
(0) fib(1) fib(0) }
fib(1) fib
(0)
Tree recursion-one fun call leading to two recursive calls
• Instead of repeatedly computing the same
Approach-II:Memoization
fib(5)
thing, we can store them in an auxillary
memory.
fib(5) = fib(4) + fib(3)
int fib_values[200]= {-1};
int fib(int n){
fib(4) = fib(3) + fib(2)
if (fib_values[n]!=-1) return (fib_values[n]);
else if (n=0) { fib_values[0] = 0; return 0;}
else if (n==1) { fib_values[1]=1; return 1;}
else { fib_values[n] = fib(n-1) + fib(n-2); return fib(1) + fib (0)
(fib_values[n]);} }
fib(3) = fib(2) + fib(1) fib(2) =
time.
buf (Size =100)
Saved registers
Saved FP
return address
(Supposed to
contain the
address of a
caller)