You are given the following problem:
The Tribonacci sequence Tn is defined as follows:
Given an integer n
, your task is to implement a function that returns the value of Tn.
For example:
n = 4
, the expected output is 4 because:
n = 25
, the expected output is 1389537.Write a function to efficiently calculate the nth Tribonacci number. Consider the constraints: 0 <= n <= 37
, and the answer is guaranteed to fit within a 32-bit integer.
This problem asks us to find the nth Tribonacci number, where the sequence is defined as T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
A straightforward approach is to use recursion directly based on the definition.
def tribonacci_recursive(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
return tribonacci_recursive(n-1) + tribonacci_recursive(n-2) + tribonacci_recursive(n-3)
This solution is simple but highly inefficient due to repeated calculations.
To avoid redundant calculations, we can use dynamic programming. Since we only need the last three Tribonacci numbers to calculate the next one, we can store them in variables and iterate.
def tribonacci_dp(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
t0, t1, t2 = 0, 1, 1
for i in range(3, n + 1):
t0, t1, t2 = t1, t2, t0 + t1 + t2
return t2
Here's the dynamic programming solution:
def tribonacci(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
t0, t1, t2 = 0, 1, 1
for i in range(3, n + 1):
tn = t0 + t1 + t2
t0, t1, t2 = t1, t2, tn
return t2