class Fibonacci{
private Map<Integer, Integer> cache= new Hashtable<Integer, Integer>();
public Fibonacci(){
}
public int fibonacciIterative(int index){
int fibonacciValue =0;
if (index == 0 || index == 1 ){
return index;
}
int lastFibonacci=fibonacciValue;
fibonacciValue +=1;
int currentFibonacciValue=0;
for (int position = 2 ; position <= index; position++){
currentFibonacciValue = fibonacciValue+lastFibonacci;
lastFibonacci=fibonacciValue;
fibonacciValue=currentFibonacciValue;
}
return currentFibonacciValue;
}
public int fibonacciRecursive(int index){
if (index < 2 ){
return index;
}
int current = cache.containsKey(index-1) ? cache.get(index-1) : fibonacciRecursive(index-1);
int previous = cache.containsKey(index-2) ? cache.get(index-2) : fibonacciRecursive(index-2);
cache.containsKey(index) current + previous;
}
}
class Main {
public static void main(String[] args) {
Fibonacci fibonacci= new Fibonacci();
System.out.println("iterative " + fibonacci.fibonacciIterative(10));
System.out.println("recursive " + fibonacci.fibonacciRecursive(10));
}
}