-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacciNumbers.java
68 lines (49 loc) · 1.66 KB
/
FibonacciNumbers.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//importing Scanner
import java.util.Scanner;
public class FibonacciNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please choose an option: \n1. Sequence found without recursion. \n2. Sequence found using recursion.");
int choice = input.nextInt();
switch(choice) {
case 1:
// non-recursive method
// four variables will act as placeholders as
// the array is traversed
int i = 0;
// j, k represent placeholders moving along the array
// where they are the values preceeding the current
// fibonacci value
// 0 and 1 are the first two values of the fibonacci sequence by desinition
long j = 1;
long k = 0;
// fib is the printed fibonacci value
long fib = 0;
System.out.println("How many values of the Fibonacci sequence would you like?");
long Num = input.nextLong();
for(i = 0; i < Num; i++) {
System.out.println(fib);
fib = j + k;
j = k;
k = fib;
}
break;
case 2:
System.out.println("How many values of the Fibonacci sequence would you like?");
long length = input.nextLong();
input.close();
for(i = 0; i < length; i++) {
System.out.println(fibonacciRecursive(i));
}
break;
default:
System.out.println("Invalid choice, try again, 1 or 2!");
}//end switch statement
}//end method
public static long fibonacciRecursive(long N){
if(N <= 1)
return N;
else
return fibonacciRecursive(N-1) + fibonacciRecursive(N-2);
}//end method
}//end class