Given a positive integer n, find the nth Tribonacci number. Tribonacci numbers, when it starts from 0, are calculaed as T(n), where T(1) = T(2) = 0, T(3) = 1, and T(n) = T(n-1) + T(n-2) + T(n-3) for n > 3. Example of first few Tribonacci numbers are 0, 0, 1, 1, 2, 4, 7, 13, 24, 44.
Observe recursive relationship from definition, implement tri(n), when n > 3 return tri(n-1) + tri(n-2) + tri(n-3), when n = 3 return 1 and when n < 3 return 0.
def tri(n):
if n < 3:
return 0
if n == 3:
return 1
return tri(n - 1) + tri(n - 2) + tri(n - 3)
n = 10
print(tri(n))
function tri(n) {
if (n < 3) {
return 0;
}
if (n === 3) {
return 1;
}
return tri(n - 1) + tri(n - 2) + tri(n - 3);
}
const n = 10;
console.log(tri(n));