...
Maybe he was asleep. I post silly things when I'm asleep too.
Don't feel bad. This is a difficult thing to wrap your brain around. The principle is this:
A list can be considered as the first item in a list and the rest of the list.
{ 5, 4, 3, 2, 1 }
a list
5, { 4, 3, 2, 1 }
first item, rest of list
Notice that the rest of the list is itself a list. Which means, of course, we can use our funny way of looking at it again.
Your list is given by the numbers { x, x-1, x-2, x-3, ..., 3, 2, 1 }. You can actually see the list when you print it out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void print_my_list(int x)
{
if (x==1)
{
cout << "1\n";
}
else
{
cout << x << ", ";
print_my_list(x-1);
}
}
int main()
{
print_my_list(5);
}
|
5, 4, 3, 2, 1 |
The above function can be seen as:
• if x == 1:
• print x (because the list is only a single element, and we are done after printing it)
• else:
• print x
• print the remainder of the list
Let's see if we can modify that to sum the elements of the list. (We'll get to that multiplication by two in a second.)
The elements are now related by adding them:
x + (x-1) + (x-2) + ... + 3 + 2 + 1
Instead of printing them, you are going to get the first element and add it to the remainder of the list's sum. See the recursion there? The first part remains the same:
• if (x == 1):
• return 1 (because the sum of a single thing is itself)
• else:
• return x + sum of remainder of list beginning with (x-1)
See if you can write code that does just that. Once you do, then you only need to throw in that multiplication by two. The trick to remember is that, even though it is true that you could factor it out, the recursive mechanism we have set up cannot do it that way, since
the function does not know whether it has the beginning of the entire list or just a sublist. So you are stuck multiplying individual elements.
fn(0) == 0
fn(1) == 2
right? Because 2*1 == 2?
fn(2) == 2*2 + 2*1
fn(3) == 2*3 + 2*2 + 2*1
Hope this helps.