Skip to content

Commit a197bfa

Browse files
authored
Update FibonacciNumbers.java
1 parent b77a438 commit a197bfa

File tree

1 file changed

+32
-14
lines changed

1 file changed

+32
-14
lines changed

FibonacciNumbers.java

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
1-
import java.util.ArrayList;
2-
import java.util.List;
3-
1+
import java.time.Instant;
42
/**
5-
* Write a function that computes the list of the first 100 Fibonacci numbers.
3+
* Write a function that computes Fibonacci sequence.
64
* By definition, the first two numbers in the Fibonacci sequence are 0 and 1,
75
* and each subsequent number is the sum of the previous two.
86
* As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
97
*/
10-
public class FibonacciNumbers {
8+
public class FibonacciNumber {
9+
1110
public static void main(String[] args){
12-
List<Double> sequence = new ArrayList<>();
13-
sequence.add(Double.valueOf(0));
14-
sequence.add(Double.valueOf(1));
15-
System.out.print("0, 1, ");
16-
for(int i=2; i<=100; i++){
17-
Double newNumber = sequence.get(i-2) + sequence.get(i-1);
18-
System.out.print(String.format("%.0f", newNumber) + ", ");
19-
sequence.add(newNumber);
20-
}
11+
int n = 40;
12+
Instant before = Instant.now();
13+
System.out.println("Fibonacci Number for n "+ n + " equals : " + fib(n));
14+
Instant after = Instant.now();
15+
System.out.println(after.toEpochMilli() - before.toEpochMilli());
16+
17+
before = Instant.now();
18+
System.out.println("Fibonacci Number for n "+ n + " with memo equals : " + fibWithMemo(n));
19+
after = Instant.now();
20+
System.out.println(after.toEpochMilli() - before.toEpochMilli());
21+
22+
}
23+
24+
private static int fib(int N) {
25+
if(N<=1) return N;
26+
return fib(N-1)+fib(N-2);
27+
}
28+
29+
private static int fibWithMemo(int N) {
30+
return getFibWithMemo(N,new int[N+1]);
31+
}
32+
33+
private static int getFibWithMemo(int N, int[] memo){
34+
if(N<=1) return N;
35+
if(memo[N]!=0) return memo[N];
36+
memo[N]=fib(N-1)+fib(N-2);
37+
return memo[N];
2138
}
2239
}
40+

0 commit comments

Comments
 (0)