The Tribonacci sequence T(n) is defined as follows:
Given n
, return the value of T(n).
n
?
n
will be a non-negative integer, and typical edge cases include values like 0, 1, 2.n
values, or is a straightforward approach sufficient?n
, storing interim results to avoid recomputation.public class Tribonacci {
public static int tribonacci(int n) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
int a = 0, b = 1, c = 1, d = 0;
for (int i = 3; i <= n; i++) {
d = a + b + c; // Compute the next Tribonacci value
a = b; // Update values for the next iteration
b = c;
c = d;
}
return d;
}
public static void main(String[] args) {
// Test cases
int n = 4;
System.out.println("T(" + n + ") = " + tribonacci(n)); // Output: 4
n = 25;
System.out.println("T(" + n + ") = " + tribonacci(n)); // Output: 1389537
}
}
n-2
times, which is linear in time complexity.Each of these variables is updated in each iteration, so we do not need extra space that grows with n
.
This approach efficiently computes the N-th Tribonacci number using iteration and simple state update.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?