Skip to content

Commit da5628f

Browse files
add lucas number
1 parent e987863 commit da5628f

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.examplehub.maths;
2+
3+
/** https://en.wikipedia.org/wiki/Lucas_number */
4+
public class LucasNumbersIteration {
5+
6+
/**
7+
* Get nth lucas number using iteration.
8+
*
9+
* @param n the nth.
10+
* @return nth lucas number.
11+
*/
12+
public static int lucas(int n) {
13+
if (n == 0) {
14+
return 2;
15+
}
16+
int first = 1;
17+
int second = 3;
18+
for (int i = 1; i < n; i++) {
19+
int temp = first + second;
20+
first = second;
21+
second = temp;
22+
}
23+
return first;
24+
}
25+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class LucasNumbersIterationTest {
8+
@Test
9+
void test() {
10+
int[] lucasNumbers = {2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123};
11+
for (int i = 0; i < lucasNumbers.length; i++) {
12+
assertEquals(lucasNumbers[i], LucasNumbersIteration.lucas(i));
13+
}
14+
}
15+
}

0 commit comments

Comments
 (0)