Induction and Recursion
暂无分享,去创建一个
Consider again the function n!. We have already seen how to compute it with a loop that multiplies the numbers 1 through n. Another way to compute n! is with a recursive program that calls itself:
$$ \begin{gathered} function FACT(n) \hfill \\ if n \leqslant 1 \hfill \\ then return 1 \hfill \\ else return n * FACT\left( {n - 1} \right) \hfill \\ end \hfill \\ \end{gathered} $$
Because\( n! = n * \left( {n - 1} \right)! \), it can be computed by solving a smaller version of the same problem and then multiplying by n. In this very simple example, the recursive program corresponds directly to a loop. If the recursion is "unwound", to compute n!, we compute \( \left( {n - 1} \right)! \), to compute \( \left( {n - 1} \right)! \) we compute \( \left( {n - 2} \right)! \), and so on until we get down to 1; then we work backwards computing \( 2 * 1 = 2 \), then \( 3 * 2 = 6 \), then \( 4 * 6 = 24 \), and so on. This form of recursion, often called tail recursion, calls itself on the "tail" of the problem and then does some simple computation (in this case, a multiplication) to incorporate the "head" of the problem. In fact, it is such a simple form of recursion that a "smart" compiler can detect it and translate it to a loop that uses O(1) space.