-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacci.java
56 lines (54 loc) · 1.07 KB
/
Fibonacci.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
public class Fibonacci
{
public static void main(String[] args)
{
if (args.length == 0)
{
System.out.println("Usage: java Fibonacci <number> [number...]");
System.out.println("Anything past the 92nd number will fail.");
}
else
{
for (int i = 0; i < args.length; i++)
{
int num = Integer.parseInt(args[i]);
if (num < 93)
{
System.out.println("\n" + num + "th Fibonacci number");
System.out.println("Fast: " + fast(num));
System.out.println("Slow: " + slow(num));
}
else
{
System.out.println("This implmentation maxes out at the 92nd number: " + fast(92));
}
System.out.println();
}
}
}
private static long fast(int nth)
{
if (nth < 3)
{
return 1;
}
long two_previous = 1;
long one_previous = 1;
long current = 2;
for (int i = 2; i < nth; i++)
{
current = two_previous + one_previous;
two_previous = one_previous;
one_previous = current;
}
return current;
}
private static long slow(int nth)
{
if (nth < 3)
{
return 1;
}
return slow(nth - 2) + slow(nth - 1);
}
}