1+ package Lecture27 ;
2+
3+
4+ public class fibonacciDynamicProg {
5+
6+ // to demonstrate time taken by DP approach and without DP approach
7+
8+ public static long STARTTIME ;
9+ public static long ENDTIME ;
10+
11+ public static void startAlgo () {
12+ STARTTIME = System .currentTimeMillis ();
13+ }
14+
15+ public static long endAlgo () {
16+ ENDTIME = System .currentTimeMillis ();
17+ return ENDTIME - STARTTIME ;
18+ }
19+
20+ public static void main (String [] args ) {
21+
22+ int nthItem = 45 ;
23+
24+ startAlgo ();
25+ System .out .println (fibonacciRecursiveOptimal (nthItem ));
26+ System .out .println ("time taken using DP approach in ms:" + endAlgo ());
27+
28+ System .out .println ();
29+
30+ startAlgo ();
31+ System .out .println (fibonacciNonOptimal (nthItem ));
32+ System .out .println ("time taken without using DP approach in ms: " + endAlgo ());
33+ }
34+
35+ // time complexity: O(n)
36+ public static int fibonacciRecursiveOptimal (int n ) {
37+ int [] memStorage = new int [n + 1 ];
38+ return fibonacciRecursiveOptimal (n , memStorage );
39+ }
40+
41+ private static int fibonacciRecursiveOptimal (int n , int [] storage ) {
42+ if (n == 0 || n == 1 ) {
43+ return n ;
44+ }
45+
46+ // accessing previously calculated factorial value of n
47+ if (storage [n ] != 0 ) {
48+ return storage [n ];
49+ }
50+ int fnm1 = fibonacciRecursiveOptimal (n - 1 , storage );
51+ int fnm2 = fibonacciRecursiveOptimal (n - 2 , storage );
52+
53+ int fibbN = fnm1 + fnm2 ;
54+
55+ storage [n ] = fibbN ;
56+
57+ return fibbN ;
58+ }
59+
60+ // without using DP approach
61+ // time complexity: Exponential
62+ public static int fibonacciNonOptimal (int n ) {
63+ if (n == 0 || n == 1 ) {
64+ return n ;
65+ }
66+
67+ int fnm1 = fibonacciNonOptimal (n - 1 );
68+ int fnm2 = fibonacciNonOptimal (n - 2 );
69+
70+ int fibbN = fnm1 + fnm2 ;
71+
72+ return fibbN ;
73+ }
74+
75+ }
76+
77+
78+ /* output:
79+ 1134903170
80+ time taken using DP approach in ms:0
81+
82+ 1134903170
83+ time taken without using DP approach in ms: 7393
84+ */
0 commit comments