private int factorial (int n) { assert n >= 0; if (n == 0) { return 1; } return n * factorial(n-1); }
- Factorial
factorial(3) => 3 * factorial(2) factorial(2) => 2 * factorial(1) factorial(1) => 1 * factorial(0) factorial(0) => 1 1 1 2 = 1 = 2 = 6
Recursive Thinking
Define the solution to a problem in terms of a solution to one or more “smaller” subproblems Define a base case, a subproblem that can be solved directly. 1 2 Tuesday, April 27, 2010