11package DynamicProgramming ;
22
3- import java .io .BufferedReader ;
4- import java .io .InputStreamReader ;
53import java .util .HashMap ;
64import java .util .Map ;
5+ import java .util .Scanner ;
76
87/**
98 * @author Varun Upadhyay (https://github.com/varunu28)
@@ -13,14 +12,16 @@ public class Fibonacci {
1312
1413 private static Map <Integer , Integer > map = new HashMap <>();
1514
16- public static void main (String [] args ) throws Exception {
1715
18- BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
19- int size = Integer .parseInt (br .readLine ());
16+ public static void main (String [] args ) {
2017
2118 // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
22- System .out .println (fibMemo (size ));
23- System .out .println (fibBotUp (size ));
19+ Scanner sc = new Scanner (System .in );
20+ int n = sc .nextInt ();
21+
22+ System .out .println (fibMemo (n ));
23+ System .out .println (fibBotUp (n ));
24+ System .out .println (fibOptimized (n ));
2425 }
2526
2627 /**
@@ -29,7 +30,7 @@ public static void main(String[] args) throws Exception {
2930 * @param n The input n for which we have to determine the fibonacci number
3031 * Outputs the nth fibonacci number
3132 **/
32- private static int fibMemo (int n ) {
33+ public static int fibMemo (int n ) {
3334 if (map .containsKey (n )) {
3435 return map .get (n );
3536 }
@@ -51,7 +52,7 @@ private static int fibMemo(int n) {
5152 * @param n The input n for which we have to determine the fibonacci number
5253 * Outputs the nth fibonacci number
5354 **/
54- private static int fibBotUp (int n ) {
55+ public static int fibBotUp (int n ) {
5556
5657 Map <Integer , Integer > fib = new HashMap <>();
5758
@@ -83,16 +84,16 @@ private static int fibBotUp(int n) {
8384 * Whereas , the above functions will take O(n) Space.
8485 * @author Shoaib Rayeen (https://github.com/shoaibrayeen)
8586 **/
86- private static int fibOptimized (int n ) {
87+ public static int fibOptimized (int n ) {
8788 if (n == 0 ) {
8889 return 0 ;
8990 }
9091 int prev = 0 , res = 1 , next ;
91- for (int i = 2 ; i < n ; i ++) {
92+ for (int i = 2 ; i <= n ; i ++) {
9293 next = prev + res ;
9394 prev = res ;
9495 res = next ;
9596 }
9697 return res ;
9798 }
98- }
99+ }
0 commit comments