In: Computer Science
Problem 3.2
A more efficient version of the function for computing Tetranacci numbers can be defined by following three steps:
Your task is to follow the three steps above, in order to implement the recursive function tetrn2 in F#.
In [ ]:
// Problem 3.2.1
let append4Sum xs =
// write your solution here
// Problem 3.2.2
let tetrn2 n =
// write your solution here
Test your function:
In [ ]:
tetrn2 33 = 747044834 // this is fast compare to `tetrn 33` call
Tetranacci Numbers
The tetranacci numbers are a generalization of the Fibonacci numbers defined by the recurrence relation
T(n) = T(n-1) + T(n-2) + T(n-3) + T(n-4)
with T(0)=0, T(1)=1, T(2)=1, T(3)=2,
For n>=4. They represent the n=4 case of the Fibonacci n-step numbers. The first few terms for n=0, 1, … are 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, …
Given a number N. The task is to find the N-th tetranacci number.
Examples:
Input: 5 Output: 4 Input: 9 Output: 108
A better solution is to use Dynamic Programming (memoisation) as there are multiple overlaps.
Given below is the recursive tree for N=10.
rec(10) / / \ \ rec(9) rec(8) rec(7) rec(6) / / \ \ rec(8) rec(7) rec(6) rec(5)
In the above partial recursion tree, rec(8), rec(7), rec(6) has been solved twice. On drawing the complete recursion tree, it has been observed that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation.
Below is the implementation of the above approach in C++
|
Output:
208
Time Complexity: O(N)
Auxiliary Space: O(N)
Next Solution
The time complexity of above is linear, but it requires extra space. Space used can be optimized in the above solution by using four variables to keep track of the previous four numbers.
Below is the implementation of the above approach
|
Output:
208
Time Complexity: O(N)
Auxiliary Space: O(1)