File tree 2 files changed +54
-0
lines changed
main/java/com/thealgorithms/dynamicprogramming
test/java/com/thealgorithms/dynamicprogramming
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .dynamicprogramming ;
2
+
3
+ /**
4
+ * The {@code Tribonacci} class provides a method to compute the n-th number in the Tribonacci sequence.
5
+ * N-th Tribonacci Number - https://leetcode.com/problems/n-th-tribonacci-number/description/
6
+ */
7
+ public class Tribonacci {
8
+
9
+ /**
10
+ * Computes the n-th Tribonacci number.
11
+ *
12
+ * @param n the index of the Tribonacci number to compute
13
+ * @return the n-th Tribonacci number
14
+ */
15
+ public static int compute (int n ) {
16
+ if (n == 0 ) return 0 ;
17
+ if (n == 1 || n == 2 ) return 1 ;
18
+
19
+ int first = 0 , second = 1 , third = 1 ;
20
+
21
+ for (int i = 3 ; i <= n ; i ++) {
22
+ int next = first + second + third ;
23
+ first = second ;
24
+ second = third ;
25
+ third = next ;
26
+ }
27
+
28
+ return third ;
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .dynamicprogramming ;
2
+
3
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4
+
5
+ import org .junit .jupiter .api .Test ;
6
+
7
+ /**
8
+ * Test class for {@code Tribonacci}.
9
+ */
10
+ public class TribonacciTest {
11
+
12
+ /**
13
+ * Tests the Tribonacci computation for a set of known values.
14
+ */
15
+ @ Test
16
+ public void testKnownValues () {
17
+ assertEquals (0 , Tribonacci .compute (0 ), "The 0th Tribonacci should be 0." );
18
+ assertEquals (1 , Tribonacci .compute (1 ), "The 1st Tribonacci should be 1." );
19
+ assertEquals (1 , Tribonacci .compute (2 ), "The 2nd Tribonacci should be 1." );
20
+ assertEquals (2 , Tribonacci .compute (3 ), "The 3rd Tribonacci should be 2." );
21
+ assertEquals (4 , Tribonacci .compute (4 ), "The 4th Tribonacci should be 4." );
22
+ assertEquals (7 , Tribonacci .compute (5 ), "The 5th Tribonacci should be 7." );
23
+ }
24
+ }
You can’t perform that action at this time.
0 commit comments