Consider the following C functions:
int f1 (int n)
{
if(n == 0 || n == 1)
return n;
else
return (2 * f1(n-1) + 3 * f1(n-2));
}
int f2(int n)
{
int i;
int X[N], Y[N], Z[N];
X[0] = Y[0] = Z[0] = 0;
X[1] = 1; Y[1] = 2; Z[1] = 3;
for(i = 2; i <= n; i++){
X[i] = Y[i-1] + Z[i-2];
Y[i] = 2 * X[i];
Z[i] = 3 * X[i];
}
return X[n];
}
The running time of and are
View worked solution
Answer: B
To find the running time of both functions, we analyze their control flow and recurrence relations:
1. Analysis of
The function is a recursive function. Let be the number of steps (or time complexity) taken by for an input .
For , the function makes two recursive calls: one to and another to , along with a constant number of basic operations.
The recurrence relation is:
with base cases and .
This recurrence is of the same form as the Fibonacci sequence recurrence. Solving the characteristic equation gives the golden ratio .
Thus, the tight bound is:
Since any exponential growth of the form (where ) is asymptotically categorized under exponential time, it is represented as in standard multiple-choice options.
2. Analysis of
The function is an iterative implementation using dynamic programming (memoization with arrays):
- Array initializations take time.
- The
forloop runs from to . - Inside the loop, all operations (array lookups, additions, and multiplications) take constant time, i.e., .
Since the loop runs exactly times, the total running time is linear:
Therefore, the running times of and are and respectively.
Free practice · Your answers on this page are not saved.
