One of the pitfalls of recursive functions is that they can tend to be slow. Some are worse than others, and choose is a particularly bad example. The code:
int choose(int n, int k) { // The base case is when k is 0 or n, // and there is just one way to choose. if (k == 0 || k == n) return 1; else // Apply the recursive formula. return choose(n-1, k-1) + choose(n-1, k); }
The problem is that there isn't one recursive call, but two. The function's time grows exponentially. We can draw a tree to show what goes into recursive calculation of n choose k:
|
Even in this small diagram, there are two important things to note:
These two factors together make the time necessary for larger numbers unnecessarily large. The way to prevent this? Remember what numbers you have already calculated, and what they were, and just use them instead of another function call. How can you do this in C++? Good question. It shall be revealed...
Back To Index