File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .io .BufferedReader ;
2+ import java .io .InputStreamReader ;
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
6+ /**
7+ *
8+ * @author Varun Upadhyay (https://github.com/varunu28)
9+ *
10+ */
11+
12+ public class Fibonacci {
13+
14+ public static Map <Integer ,Integer > map = new HashMap <Integer ,Integer >();
15+
16+ public static void main (String [] args ) throws Exception {
17+
18+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
19+ int n = Integer .parseInt (br .readLine ());
20+
21+ System .out .println (fib (n )); // Returns 8 for n = 6
22+ }
23+
24+ /**
25+ * This method finds the nth fibonacci number using memoization technique
26+ *
27+ * @param n The input n for which we have to determine the fibonacci number
28+ * Outputs the nth fibonacci number
29+ **/
30+
31+ public static int fib (int n ) {
32+ if (map .containsKey (n )) {
33+ return map .get (n );
34+ }
35+
36+ int f ;
37+
38+ if (n <= 2 ) {
39+ f = 1 ;
40+ }
41+ else {
42+ f = fib (n -1 ) + fib (n -2 );
43+ map .put (n ,f );
44+ }
45+
46+ return f ;
47+ }
48+ }
49+
You can’t perform that action at this time.
0 commit comments