public returnType recursiveAlgorithm(someType input) {
someType simpler_input;
if (baseCase(input)) {
return baseComputation(input);
}
else {
simpler_input = simplify(input);
return computation(input, recursiveAlgorithm(simpler_input));
} // recursive case
} // recursiveAlgorithm
n!, the factorial
of n, we might write:
public int factorial(int n) {
if (n == 0) {
return 1;
}
else {
return n*factorial(n-1);
}
} // factorial
Note that this almost precisely mimics the way in which a mathematician
might define factorial over the integers.
/**
* Compute x^n for integers x and n
* pre: n >= 0
* pre: x > 0
* pre: x^n < maxint (can't really check this, but ...)
* post: returns x^n
*/
public int exp(int x, int n) {
int result = 1; // The result, computed as we go
for(int i = 0; i < n; ++i) {
result *= x;
}
return result;
} // exp
public int exp(int x, int n) {
int tmp; // Temporary value, used for int. calcs.
if (n == 0) {
// x^0 = 1 for x != 0
return 1;
} // n is 0
else if (even(n)) {
// x^(2k) = x^k * x^k
tmp = exp(x, n/2);
return tmp*tmp;
} // n is even
else { // n is odd
// x^(k+1) = x * x^k
tmp = exp(x, n-1);
return x*tmp;
} // n is odd
} // exp
public int minimum_stamps(int price, int[] counts) {
int min = -1; // The minimum
int submin; // The minimum for a smaller price
int[] subcounts = new int[stamp_values.length];
// Counts for smaller price
// Sanity check
if (price == 0) {
for(int i = 0; i < stamp_values.length; ++i) {
counts[i] = 0;
} //for
return 0;
}
// Try each stamp value
for(int i = 0; i < stamp_values.length; ++i) {
if (price >= stamp_values[i]) {
submin = minimum_stamps(price-stamp_values[i],subcounts);
// If it's a valid number of stamps, and "better" than our
// previous best, update our best
if ( (submin > -1) &&
( (submin+1 < min) || (min == -1) ) ) {
min = submin+1;
for(int j = 0; j < stamp_values.length; ++j) {
counts[j] = subcounts[j];
} // for
counts[i] += 1;
} // A better value
} // if the value is smaller than the price
} // for
// That's it, we're done
return min;
} // minimum_stamps
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Tue Oct 7 17:12:58 1997.
This page generated on Wed Nov 5 12:38:38 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu