forked from careercup/ctci
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacciFB.java
More file actions
43 lines (38 loc) · 1.04 KB
/
FibonacciFB.java
File metadata and controls
43 lines (38 loc) · 1.04 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
package Introduction;
public class FibonacciFB {
public static int max = 100; // Make this as big as you want! (Though you'll exceed the bounds of a long around 46)
public static int[] fib = new int[max];
public static int fibonacci(int i) {
if (i == 0) {
return 0;
}
if (i == 1) {
return 1;
}
if (fib[i] != 0) {
return fib[i];
}
fib[i] = fibonacci(i - 1) + fibonacci(i - 2);
return fib[i];
}
/**
* @param args
*/
public static void main(String[] args) {
int trials = 10; // Run code multiple times to compute average time.
double[] times = new double[max]; // Store times
for (int j = 0; j < trials; j++) { // Run this 10 times to compute
for (int i = 0; i < max; i++) {
fib = new int[max];
long start = System.currentTimeMillis();
fibonacci(i);
long end = System.currentTimeMillis();
long time = end - start;
times[i] += time;
}
}
for (int j = 0; j < max; j++) {
System.out.println(j + ": " + times[j] / trials + "ms");
}
}
}