Add Tribonacci Numbers (fixes #4646) (#4959)

This commit is contained in:
Doksanbir
2023-11-26 14:34:13 +03:00
committed by GitHub
parent b1efd4e34b
commit 1518e84fb9
2 changed files with 54 additions and 0 deletions

View File

@ -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;
}
}