-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExample3.java
More file actions
95 lines (66 loc) · 2.15 KB
/
Example3.java
File metadata and controls
95 lines (66 loc) · 2.15 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package applications.algorithms;
import java.util.HashMap;
import java.util.Map;
/** Category: Algorithms
* ID: Example13
* Description: Fibonacci nth value calculation with various methods
* Taken From:
* Details:
* TODO
*/
public class Example3 {
public static int recursive_fib(int n){
if(n < 0){
throw new IllegalArgumentException("Cannot calculate Fibonacci sequence for negative numbers");
}
int[] rslt_base = {0, 1};
if(n < 2){
return rslt_base[n];
}
return recursive_fib(n-1) + recursive_fib(n-2);
}
public static int iterative_fib(int n){
if(n < 0){
throw new IllegalArgumentException("Cannot calculate Fibonacci sequence for negative numbers");
}
int[] rslt_base = {0, 1};
if(n < 2){
return rslt_base[n];
}
int previous = 1;
int previous_previous = 0;
int rslt = 0;
for(int i=2; i<=n; ++i){
rslt = previous + previous_previous;
previous_previous = previous;
previous = rslt;
}
return rslt;
}
public static int memo_fib(int n){
if(n < 0){
throw new IllegalArgumentException("Cannot calculate Fibonacci sequence for negative numbers");
}
Map<Integer, Integer> values = new HashMap<>();
values.put(0, 0);
values.put(1, 1);
if( !values.containsKey(n)){
values.put(n, memo_fib(n-1) + memo_fib(n-2));
}
return values.get(n);
}
public static void main(String[] args){
int rslt = Example3.recursive_fib(5);
if (rslt != 5){
System.out.println("Recursive Fibonacci: Invalid Fibonacci result " + rslt + "not equal to 5");
}
rslt = Example3.iterative_fib(5);
if (rslt != 5){
System.out.println("Iterative Fibonacci: Invalid Fibonacci result " + rslt + "not equal to 5");
}
rslt = Example3.memo_fib(5);
if (rslt != 5){
System.out.println("Memo Fibonacci: Invalid Fibonacci result " + rslt + "not equal to 5");
}
}
}