Lab#03
Lab#03
LAB # 03
RECURSION
What is Recursion?
In a base case, we compute the result immediately given the inputs to the function.
In a recursive step, we compute the result with the help of one or more recursive
calls to this same function, but with the inputs somehow reduced in size or
complexity, closer to a base.
Memoization
Memoization ensures that method does not execute more than once for same inputs by
storing the results in the data structure(Usually Hashtable or HashMap or Array).
Implementation
Let’s understand with the help of Fibonacci example. Below is a sample of fibonacci
series.
0,1,1,2,3,5,8,13,21,34,55,89,144….
F(n)= F(n-1)+F(n-2)
if( n == 0 ) return 0;
if( n == 1 ) return 1;
System.out.println("Calculating fibonacci number for: "+n);
return (fibonacci(n-1) + fibonacci(n-2));
If you notice here, we are calculating f(3) twice and f(2) thrice here, we can avoid
duplication with the helping of caching the results. We will use one instance variable
memoizeTable for caching the result.
Check if n is already present in memoizeTable, if yes, return the value
If n is not present in memoizeTable, then compute and put the result in memoizeTable.
Sample Program#1
import java.util.HashMap;
import java.util.Map;
if( n == 0 ) return 0;
if( n == 1 ) return 1;
if( this.memoizeTable.containsKey(n) )
{
System.out.println("Getting value from computed result for "+n);
return this.memoizeTable.get(n);
}
this.memoizeTable.put(n, result);
return result;
if( n == 0 ) return 0;
if( n == 1 ) return 1;
}
}
You can see, we are not computing fibonacci number for 2 and 3 more than once.
LAB TASK
1. Write a program which takes an integer value (k) as input and prints the sequence of
numbers from k to 0 in descending order.
HOME TASK
1. Write a java program to find the N-th term in the Fibonacci series using Memoization.
4. Write a recursive program to find the greatest common divisor (GCD) of two
numbers using Euclid's algorithm.