|
n! = n × (n−1)! with: 0! = 1 |
|
|
int factorial( int n ) { if ( n == 0 /* the base cases */ ) { return 1; // The readily available solution for the base case } else { /* ---------------------------------- Delegate the problem: hire someone to solve (n-1)! ---------------------------------- */ sol1 = factorial ( n−1 ); /* ------------------------------------------- Use the solutions of the smaller (n-1)! to solve my problem: ------------------------------------------- */ mySol = n * sol1; return mySol; } } |
public class Recurse1 { public static int factorial( int n ) { int sol1, mySol; // Define variable... if ( n == 0 /* the base cases */ ) { return 1; // The readily available solution for the base case } else { sol1 = factorial ( n-1 ); // Let "someone else" (= factorial(n-1) ) // solve the smaller problem mySol = n * sol1; // Use the solution of the smaller problem // to solve my own problem return mySol; // Return my solution } } } |
How to run the program:
|
|
public class Recurse1 { public static int factorial( int n ) { int sol1, solution; // Define variable... if ( n == 0 /* the base cases */ ) { return 1; // The readily available solution for the base case } else { // factorial(n) is solved using solutions of // the smaller problem factorial(n-1)... sol1 = factorial ( n-1 ); // Solve a smaller problem solution = n * sol1; // Use the solution of the smaller problem // to solve the original problem return solution; } } } |
|