Skip to content

Commit 61afbc4

Browse files
add lucas dynamic programming
1 parent da5628f commit 61afbc4

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.examplehub.dynamicprogramming;
2+
3+
/** https://en.wikipedia.org/wiki/Lucas_number */
4+
public class LucasDP {
5+
6+
/**
7+
* Return nth lucas number using dynamic programming.
8+
*
9+
* @param n the nth.
10+
* @return the nth number of lucas series.
11+
*/
12+
public static int lucas(int n) {
13+
if (n == 0) {
14+
return 2;
15+
}
16+
int[] lucasNumbers = new int[n + 1];
17+
lucasNumbers[0] = 2;
18+
lucasNumbers[1] = 1;
19+
for (int i = 2; i <= n; i++) {
20+
lucasNumbers[i] = lucasNumbers[i - 1] + lucasNumbers[i - 2];
21+
}
22+
return lucasNumbers[n];
23+
}
24+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.examplehub.dynamicprogramming;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class LucasDPTest {
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], LucasDP.lucas(i));
13+
}
14+
}
15+
}

0 commit comments

Comments
 (0)