Memoized version of Fibonacci number calculation using only one variable in Java
Fibonacci number can be calculated using different techniques. Most common recursive technique is brute force where we calculate Fibonacci number by repeatedly calling the method of numbers less by one and less by two. In this technique, we do not care the fact the previous Fibonacci number may have been calculated. However, in Memoized technique, we store the results in some array or variable and calculate new values from old calculated values. Source codes for brute force technique, memorized with array and memoized with one variable are given below.
1) Source code for Brute force technique
public class Fibonacci {
int recursiveCalls= 0;
public int fib(int n){
recursiveCalls++;
if( n==0 || n==1){
return 1;
}
else{
return fib(n-2) + fib(n-1);
}
}
public static void main(String[] args) {
Fibonacci f = new Fibonacci();
System.out.println("Fib (30): " + f.fib(30));
System.out.println("Counter: " + f.recursiveCalls);
}
}
2) Source code for Memoized technique using Table Array
public class Fibonacci {
int recursiveCalls= 0 ;
int memoizedFib(int n){
int f[]= new int[n+1];
return recursiveFib(f,n);
}
int recursiveFib(int f[], int n){
recursiveCalls++;
if ( n==0 || n==1)
f[n] = 1;
else{
if (f[n-1] == 0)
recursiveFib(f, n-1);
if (f[n-2] == 0)
recursiveFib(f, n-2);
f[n] = f[n-2] + f[n-1];
}
return f[n];
}
}
3) Source code for Memoized technique using one variable
public class Fibonacci {
int recursiveCalls = 0;
int a=0;
int fib(int n){
recursiveCalls ++;
if (n==1){
a = 1;
return 0 + a;
}
else{
int b = fib(n-1);
int c = a + b;
a = b;
return c;
}
}
}
The number of recursive Calls made for calculation of Fibonacci of 30 is 2692537 in Brute force technique where as it is 30 in memoized techniques