I am preparing for computer science AP exam and have recursions as one of the topics. Being reletively new to programming I wanted to know if there is any easy way, or a few tips you would like to offer regarding recursion. On the exam we have no access to the computer (obviously). So what is an easy way to find solutions to recursions. For example the following is a problem diectly from my book.
public static int mystrey(int x)
{
if(x == 0)
{
return 0;
}
else
{
return (x + mystrey(x/10)+mystrey(x/4);
}
}
What would be the return value if mystrey(10) is called?
Well if you use recursion it’s good to know the meaning of the function. This helps a lot to understand why the method is recursive. Furthermore calculating the function on paper is mostly done by a method called “dispatching”. In this case you see that
mystrey(0) = 0(the if-case).If you want to calculate the value of mystrey(10) you know it’s a sum of 10, mystrey(1) and mystrey(2).
You simply create a table where one can put:
we now calculate the value of the function with the highest argument so mystrey(2):
we know the value of f(0), it’s already in the table, so
now we calculate
f(1)=1We finally conclude that
f(10)=10+f(1)+f(2)=10+1+2=13.Using a table becomes helpfull when there is a lot of recursion. A lot of times recursion results in overlap, where a huge number of times the function with the same arguments must be computed. With dispatching one can avoid the “branching”. One can see recursion as a tree. Because
f(0)has a fixed value this is called the “base case” and are the leafs of the tree. The other function values are called “branches”. When calculatingf(10)we need to calculatef(1)andf(2), so one could draw edges fromf(10)tof(2)andf(1). And so one could repeat the process.Also in most cases a good programmer will program this dispatching in the algorithm. This is of course done by declaring an array an store values in the array and perform a lookup on it.
In recursion theory it’s common the recursion consist of two parts: a base case part, where answers are “hard coded” for some function calls (in your example when
x=0), and a recursive part wheref(x)is written in parts off(y). In general one can use dispatching by building an intial table with the hard coded values, and calculate the value of a specificxby starting to fill in the entry ofxin the table, and work down.