forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
30 changes: 30 additions & 0 deletions
30
src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package com.thealgorithms.dynamicprogramming; | ||
|
||
/** | ||
* The {@code Tribonacci} class provides a method to compute the n-th number in the Tribonacci sequence. | ||
* N-th Tribonacci Number - https://leetcode.com/problems/n-th-tribonacci-number/description/ | ||
*/ | ||
public class Tribonacci { | ||
|
||
/** | ||
* Computes the n-th Tribonacci number. | ||
* | ||
* @param n the index of the Tribonacci number to compute | ||
* @return the n-th Tribonacci number | ||
*/ | ||
public static int compute(int n) { | ||
if (n == 0) return 0; | ||
if (n == 1 || n == 2) return 1; | ||
|
||
int first = 0, second = 1, third = 1; | ||
|
||
for (int i = 3; i <= n; i++) { | ||
int next = first + second + third; | ||
first = second; | ||
second = third; | ||
third = next; | ||
} | ||
|
||
return third; | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package com.thealgorithms.dynamicprogramming; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
/** | ||
* Test class for {@code Tribonacci}. | ||
*/ | ||
public class TribonacciTest { | ||
|
||
/** | ||
* Tests the Tribonacci computation for a set of known values. | ||
*/ | ||
@Test | ||
public void testKnownValues() { | ||
assertEquals(0, Tribonacci.compute(0), "The 0th Tribonacci should be 0."); | ||
assertEquals(1, Tribonacci.compute(1), "The 1st Tribonacci should be 1."); | ||
assertEquals(1, Tribonacci.compute(2), "The 2nd Tribonacci should be 1."); | ||
assertEquals(2, Tribonacci.compute(3), "The 3rd Tribonacci should be 2."); | ||
assertEquals(4, Tribonacci.compute(4), "The 4th Tribonacci should be 4."); | ||
assertEquals(7, Tribonacci.compute(5), "The 5th Tribonacci should be 7."); | ||
} | ||
} |