-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibSequence.java
More file actions
46 lines (40 loc) · 1014 Bytes
/
Copy pathFibSequence.java
File metadata and controls
46 lines (40 loc) · 1014 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
import java.util.HashMap;
import java.util.Scanner;
public class FibSequence {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Enter the nth element you would like in the Fibonnaci Sequence:");
int input = in.nextInt();
HashMap<Integer, Integer> fibonnaciMap = new HashMap<Integer, Integer>();
int nthElement = input;
int count = 0;
int result = 0;
while(count < nthElement){
result = Fibonnaci(count, fibonnaciMap);
count++;
}
System.out.println(result);
}
}
public static int Fibonnaci(int n, HashMap<Integer, Integer> fibonnaciMap){
if(fibonnaciMap.get(n) != null){
return fibonnaciMap.get(n);
}
else if(n == 0){
return 0;
}
else if (n == 1) {
return 1;
}
else if (n > 1) {
int first = Fibonnaci(n - 1, fibonnaciMap);
int second = Fibonnaci(n - 2, fibonnaciMap);
fibonnaciMap.put(n, first + second);
return fibonnaciMap.get(n);
}
else{
return 0;
}
}
}