Problem of the Day
Problem:
A certain species of tree always produces branches in pairs, and can be modeled as follows: if it has n = 0 forks, it only has one "segment" of wood, its trunk. If it has n = 1 fork level it has three segments of wood: the trunk and two branches. And if it has n = 2 fork levels it has seven segments of wood, as shown.
Identify which recursive function will return the correct number of segments of wood, given a fork level n
.
public static int recurse(int n)
{
if (n == 0)
return 1;
else
return 2 + recurse(n - 1);
}public static int recurse(int n)
{
if (n == 0)
return 1;
else
return 1 + 2 * recurse(n - 1);
}public static int recurse(int n)
{
if (n <= 1)
return 1;
else
return 1 + 2 * recurse(n - 1);
}public static int recurse(int n)
{
if (n == 0)
return 0;
else
return 1 + 2 * recurse(n - 1);
}
The correct answer is b. The base case is 0 forks, which should return a value of 1. The recursive call for values of n > 1
includes the current "branch" (one segment of wood) as well as the pieces of wood for the 2 additional branches (or 2 * recurse(n - 1)
).