-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_Fibonacci.java
More file actions
44 lines (36 loc) · 957 Bytes
/
Copy path07_Fibonacci.java
File metadata and controls
44 lines (36 loc) · 957 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
package hw06fibo;
public class Fibonacci {
/**
* Implement by https://cs.wikipedia.org/wiki/Fibonacciho_posloupnost
*
*
*/
public long implementFibonacciByRecursion(int n) {
if (n <= 1) {
return n;
} else {
return implementFibonacciByRecursion(n - 1) + implementFibonacciByRecursion(n - 2);
}
}
/**
* Implement by5 https://cs.wikipedia.org/wiki/Fibonacciho_posloupnost
*
*
*/
public long implementFibonacciByFor(int n) {
if (n < 0) {
throw new IllegalArgumentException("Parameter n must be non-negative.");
}
if (n <= 1) {
return n;
}
long fibPrev = 0;
long fibCurrent = 1;
for (int i = 2; i <= n; i++) {
long temp = fibCurrent;
fibCurrent = fibPrev + fibCurrent;
fibPrev = temp;
}
return fibCurrent;
}
}