Uh oh!
There was an error while loading. Please reload this page.
forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacci.java
More file actions
Latest commit
75 lines (58 loc) · 1.7 KB
/
Copy pathFibonacci.java
File metadata and controls
75 lines (58 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.HashMap;
importjava.util.Map;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
publicclassFibonacci {
privatestaticMap<Integer,Integer> map = newHashMap<Integer,Integer>();
publicstaticvoidmain(String[] args) throwsException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
intn = Integer.parseInt(br.readLine());
System.out.println(fibMemo(n)); // Returns 8 for n = 6
System.out.println(fibBotUp(n)); // Returns 8 for n = 6
}
/**
* This method finds the nth fibonacci number using memoization technique
*
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
privatestaticintfibMemo(intn) {
if (map.containsKey(n)) {
returnmap.get(n);
}
intf;
if (n <= 2) {
f = 1;
}
else {
f = fibMemo(n-1) + fibMemo(n-2);
map.put(n,f);
}
returnf;
}
/**
* This method finds the nth fibonacci number using bottom up
*
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/
privatestaticintfibBotUp(intn) {
Map<Integer,Integer> fib = newHashMap<Integer,Integer>();
for (inti=1;i<n+1;i++) {
intf = 1;
if (i<=2) {
f = 1;
}
else {
f = fib.get(i-1) + fib.get(i-2);
}
fib.put(i, f);
}
returnfib.get(n);
}
}