|
|
|
n! = n × (n − 1)! where: 0! = 1 |
Notice that:
|
10! = 10 × 9! |
To compute 10!, we need to value of 9!
|
9! = 362880 |
Then, we can solve the original problem (10!) very easily:
10! = 10 × 362880 = 3628800 |
|
Example: the factorial(n) problem has the recursive property
|
|
I like to describe this recursive solution procedure as:
|
|
|
ReturnType solveProblem( n ) { if ( n is one of the base cases ) { return ( the readily available solution for that base case ); } else { /* ----------------------------------------------------------- Delegate the problem: hire someone to solve a (one or more) smaller problems ------------------------------------------------------------ */ sol1 = solveProblem ( n−1 ); // n−1 < n sol2 = solveProblem ( n−2 ); // n−2 < n ... /* ----------------------------------------------------------- Use the solutions of the smaller problems n−1, n−2, ... to solve my problem: ------------------------------------------------------------ */ mySol = Solve "problem(n)" using sol1, sol1, ... return ( mySol ); } } |
|
|
ReturnType solveProblem( n ) { if ( n is one of the base cases ) { return ( the readily available solution for that base case ); } else { /* ----------------------------------------------------------- Delegate the problem: hire someone to solve a (one or more) smaller problems ------------------------------------------------------------ */ sol1 = solveProblem ( n−1 ); // n−1 < n sol2 = solveProblem ( n−2 ); // n−2 < n ... /* ----------------------------------------------------------- Use the solutions of the smaller problems n−1, n−2, ... to solve my problem: ------------------------------------------------------------ */ mySol = Solve "problem(n)" using sol1, sol1, ... return ( mySol ); } } |
Notable fact:
|
|
We will see some recursive methods in the next few webpages.
Make sure that the problem has the recursive property (if the problem does not have the recursive property, then you cannot use recursion !!!)
|
We will now look at some examples of the recursive algorithm technique.