File tree 1 file changed +28
-2
lines changed
1 file changed +28
-2
lines changed Original file line number Diff line number Diff line change @@ -18,7 +18,8 @@ public static void main(String[] args) throws Exception {
18
18
BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
19
19
int n = Integer .parseInt (br .readLine ());
20
20
21
- System .out .println (fib (n )); // Returns 8 for n = 6
21
+ System .out .println (fibMemo (n )); // Returns 8 for n = 6
22
+ System .out .println (fibBotUp (n )); // Returns 8 for n = 6
22
23
}
23
24
24
25
/**
@@ -28,7 +29,7 @@ public static void main(String[] args) throws Exception {
28
29
* Outputs the nth fibonacci number
29
30
**/
30
31
31
- public static int fib (int n ) {
32
+ public static int fibMemo (int n ) {
32
33
if (map .containsKey (n )) {
33
34
return map .get (n );
34
35
}
@@ -45,5 +46,30 @@ public static int fib(int n) {
45
46
46
47
return f ;
47
48
}
49
+
50
+ /**
51
+ * This method finds the nth fibonacci number using bottom up
52
+ *
53
+ * @param n The input n for which we have to determine the fibonacci number
54
+ * Outputs the nth fibonacci number
55
+ **/
56
+
57
+ public static int fibBotUp (int n ) {
58
+
59
+ Map <Integer ,Integer > fib = new HashMap <Integer ,Integer >();
60
+
61
+ for (int i =1 ;i <n +1 ;i ++) {
62
+ int f = 1 ;
63
+ if (i <=2 ) {
64
+ f = 1 ;
65
+ }
66
+ else {
67
+ f = fib .get (i -1 ) + fib .get (i -2 );
68
+ }
69
+ fib .put (i , f );
70
+ }
71
+
72
+ return fib .get (n );
73
+ }
48
74
}
49
75
You can’t perform that action at this time.
0 commit comments