forked from AndrewProgramming/JavaTutorialCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputeFibonacci.java
More file actions
46 lines (39 loc) · 1018 Bytes
/
ComputeFibonacci.java
File metadata and controls
46 lines (39 loc) · 1018 Bytes
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
package recursive;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ComputeFibonacci {
/**
* Main method
*/
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter an index for a Fibonacci number: ");
int index = input.nextInt();
// Find and display the Fibonacci number
System.out.println("The Fibonacci number at index "
+ index + " is " + fib(index));
}
private static Map map = new HashMap<>();
/**
* The method for finding the Fibonacci number
*/
public static long fib(long index) {
if (map.containsKey(index)) {
return (long) map.get(index);
}
if (index == 0) // Base case
{
return 0;
} else if (index == 1) // Base case
{
return 1;
} else // Reduction and recursive calls
{
long result = fib(index - 1) + fib(index - 2);
map.put(index, result);
return result;
}
}
}