Skip to content

Commit 0d4cfba

Browse files
committed
Added Fibanacci using memoization
1 parent affcbac commit 0d4cfba

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Dynamic Programming/Fibonacci.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+

0 commit comments

Comments
 (0)