|
1 |
| -import java.util.ArrayList; |
2 |
| -import java.util.List; |
3 |
| - |
| 1 | +import java.time.Instant; |
4 | 2 | /**
|
5 |
| - * Write a function that computes the list of the first 100 Fibonacci numbers. |
| 3 | + * Write a function that computes Fibonacci sequence. |
6 | 4 | * By definition, the first two numbers in the Fibonacci sequence are 0 and 1,
|
7 | 5 | * and each subsequent number is the sum of the previous two.
|
8 | 6 | * As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
|
9 | 7 | */
|
10 |
| -public class FibonacciNumbers { |
| 8 | +public class FibonacciNumber { |
| 9 | + |
11 | 10 | 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]; |
21 | 38 | }
|
22 | 39 | }
|
| 40 | + |
0 commit comments