Recursion and Factorials
Introduction to Recursion
What recursion means
Recursion is a way to solve a problem in which a function calls itself. A recursive solution reduces a problem to a smaller version of the same problem, continuing until it reaches a case that can be answered directly.
Factorials provide a simple example of how a problem can be expressed recursively.
Factorials
For a nonnegative integer n, the factorial of n, written n!, is the product of the positive integers from n down to 1. For example:
4!=4×3×2×1=24
2!=2×1=2
1!=1
By definition, $0! = 1.
A function called fact could take a nonnegative integer as its input and return its factorial.
Expressing factorials recursively
For n≥1, the factorial product can be separated into its first factor, n, and the product of the remaining factors:
This equation expresses the factorial of n in terms of the factorial of a smaller number, n−1. For instance:
2!=2×1!=2×1=2
1!=1×0!=1×1=1
However, the equation cannot be used for every nonnegative integer. If n=0, it would require calculating (−1)!, which is not defined.
A complete factorial definition therefore has two cases:
The first case is the recursive case: it uses a smaller factorial to calculate the current one. The second case is the base case: it supplies a direct answer and stops the repeated reduction.
A recursive definition needs a base case as well as a rule that reduces the problem. Without the base case, the definition would keep asking for smaller factorials without reaching a defined answer.
Applying the definition to 3!
Using the recursive case, since 3≥1:
The same rule can then be applied to 2!, and then to 1!, until the base case is reached:
Because 0!=1, the calculation terminates with the correct result.
Key ideas
Recursive case: reduces the current problem to a smaller instance of itself, as in n!=n×(n−1)! for n≥1.
Base case: provides an answer directly, as in 0!=1.
A recursive factorial function follows these cases: it returns 1 when its input is 0; otherwise, it multiplies the input by the factorial of one less than that input.

Ask anything
We've read this whole study set, so questions about it get the best answers.