Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathLucasSeries.java
More file actions
Latest commit
69 lines (65 loc) · 2.07 KB
/
Copy pathLucasSeries.java
File metadata and controls
69 lines (65 loc) · 2.07 KB
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
68
69
packagecom.thealgorithms.maths;
/**
* Utility class for calculating Lucas numbers.
* The Lucas sequence is similar to the Fibonacci sequence but starts with 2 and
* 1.
* The sequence follows: L(n) = L(n-1) + L(n-2)
* Starting values: L(1) = 2, L(2) = 1
* Sequence: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ...
*
* @see <a href="https://en.wikipedia.org/wiki/Lucas_number">Lucas Number</a>
* @author TheAlgorithms Contributors
*/
publicfinalclassLucasSeries {
privateLucasSeries() {
}
/**
* Calculate the nth Lucas number using recursion.
* Time Complexity: O(2^n) - exponential due to recursive calls
* Space Complexity: O(n) - recursion depth
*
* @param n the position in the Lucas sequence (1-indexed, must be positive)
* @return the nth Lucas number
* @throws IllegalArgumentException if n is less than 1
*/
publicstaticintlucasSeries(intn) {
if (n < 1) {
thrownewIllegalArgumentException("Input must be a positive integer. Provided: " + n);
}
if (n == 1) {
return2;
}
if (n == 2) {
return1;
}
returnlucasSeries(n - 1) + lucasSeries(n - 2);
}
/**
* Calculate the nth Lucas number using iteration.
* Time Complexity: O(n) - single loop through n iterations
* Space Complexity: O(1) - constant space usage
*
* @param n the position in the Lucas sequence (1-indexed, must be positive)
* @return the nth Lucas number
* @throws IllegalArgumentException if n is less than 1
*/
publicstaticintlucasSeriesIteration(intn) {
if (n < 1) {
thrownewIllegalArgumentException("Input must be a positive integer. Provided: " + n);
}
if (n == 1) {
return2;
}
if (n == 2) {
return1;
}
intprevious = 2;
intcurrent = 1;
for (inti = 2; i < n; i++) {
intnext = previous + current;
previous = current;
current = next;
}
returncurrent;
}
}