Skip to content

Commit 1518e84

Browse files
authored
Add Tribonacci Numbers (fixes TheAlgorithms#4646) (TheAlgorithms#4959)
1 parent b1efd4e commit 1518e84

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}

0 commit comments

Comments
 (0)