$ $
E.g.:
f(n)=f(n−1)+1Finding closed-form solutions requires that we provide initial conditions:
f(0)=1
Draw a recursion trace for split(3)
:
public static int split(int n) {
if (n == 0) {
return 1;
} else {
return split(n - 1) + split(n - 1);
}
}
Express the number of activation records as a recurrence relation:
T(0)=1
T(n)=1+2T(n−1)
More typically, we want to count the number of steps executed by a recursive algorithm:
public static int split1(int n) { for (int i = 0; i < n + 10; i++) { //BASIC OPERATION HERE. } if (n == 0) { return 1; } else { return split(n - 1) + split(n - 1); } }
T(0)=10
T(n)=n+10+2T(n−1)
Typically:
Initial Conditions
T(size_of_base_case)=#operations_required_for_base_case
Recurrence Relation
T(n)=#operations_in_call+#recursive_calls×T(size_of_calls)
Develop a recurrence that describes the number of multiplication operations performed by the following code block:
public static int fun(int n) {
if (n == 0) {
return 5;
} else {
int sum = 1;
for (int i = 0; i < 4; i++) {
sum *= 2;
}
return sum * fun(n - 1);
}
}
}
T(0)=??
T(n)=??
public static int fun(int n) { if (n == 0) { return 5; } else { int sum = 1; for (int i = 0; i < 4; i++) { sum *= 2; // Four here. } return sum * fun(n - 1); // One here. } } }
T(0)=0
T(n)=5+T(n−1)
Write a recurrence relation that describes the number of additions performed by this method.
public static int fun1(int n) {
if (n == 0) {
return 20;
} else {
int result = 2 * n;
return result - (fun(n - 1) + fun(n - 1));
}
}
Next time...