criskgl
7/25/2019 - 12:10 PM

Fibonacci


public class Fibo {

	public static void main(String[] args) {
		int n = 6;
		System.out.println("Naive Fib of "+n+" "+naiveFibo(n));
		long [] memo = new long[n+1];
		System.out.println("Dynamic Fib of "+n+" "+dynamicFibo(n, memo));
		System.out.println("Bottom-Up Fib of "+n+" "+bottomUpFibo(n));
	}
	
	//NAIVE RECURSIVE APPROACH
	public static int naiveFibo(int n){
		if(n == 1 || n == 2){
			return 1;
		}else{
			return naiveFibo(n-1) + naiveFibo(n-2);
		}
	}
	
	//DYNAMIC APPROACH USING MEMOIZATION
	public static long dynamicFibo(int n, long[] memo){
		long temp = memo[n];
		long result;
		if(temp != 0){
			return temp;
		}
		if(n == 1 || n == 2){
			result = 1;
		}else{
			result = dynamicFibo(n-1, memo) + dynamicFibo(n-2, memo);
		}
		memo[n] = result;
		return result;
	}
	//BOTTOM UP APPROACH
	public static long bottomUpFibo(int n){
		long[] arr = new long[n];
		arr[0] = 1;
		arr[1] = 1;
		for(int i = 2; i < n; i++){
			arr[i] = arr[i-1] + arr[i-2];
		}
		return arr[n-1];
	}
}