/**
Compute the nth Fibonacci number.
pre: n >= 0
pre: fib(n) <= maximum integer
post: returns the nth fibonacci number
*/
public static int fib(int n) {
// Base case
if ((n == 0) || (n == 1)) {
return 1;
} // base case
// Recursive case
else {
return fib(n-1) + fib(n-2);
} // recursive case
} // fib(n)
/**
Compute the nth Fibonacci number.
pre: n >= 0
pre: fib(n) <= maximum integer
post: returns the nth fibonacci number
*/
public static int newfib(int n) {
int[] solutions = new int[n+1];
// Fill in the intial solutions
solutions[0] = 1;
solutions[1] = 1;
// Fill in the remaining solutions
for(int i = 2; i <=n; ++i) {
solutions[i] = solutions[i-1] + solutions[i-2]
} // for
// That's it
return solutions[n];
} // newfib
/**
Compute the nth Fibonacci number.
pre: n >= 0
pre: fib(n) <= maximum integer
post: returns the nth fibonacci number
*/
public static int newerfib(int n) {
int[] solutions = new int[n+1];
// We'll use 0 to indicate "no solution yet"
for(int i = 0; i <= n; ++i) {
solutions[i] = 0;
}
// Compute the fibonacci using this helper array
return newerfib(n,solutions);
} // newerfib(int)
/**
Compute the nth Fibonacci number.
pre: n >= 0
pre: fib(n) <= maximum integer
pre: solutions.length >= n+1
post: returns the nth fibonacci number
*/
public static int newerfib(int n, int[] solutions) {
// Deal with precomputed solutions. Note that return
// immediately exits the routine, so I don't need an
// else clause.
if (solutions[n] != 0) {
return solutions[n];
}
// Base case
if ((n == 0) || (n == 1)) {
solutions[n] = 1;
} // base case
// Recursive case
else {
solutions[n] = newerfib(n-1,solutions) + newerfib(n-2,solutions);
} // recursive case
return solutions[n];
} // newerfib(int,int[])
public returnType tailRecursiveAlgorithm(someType input, SomeType extraInfo) {
someType simpler_input;
if (baseCase(input)) {
return baseComputation(input);
}
else {
simpler_input = simplify(input);
return recursiveAlgorithm(simpler_input,more_stuff));
} // recursive case
} // tailRecursiveAlgorithm
public int factorial(int n) {
return tr_factorial(n, 1);
}
public int tr_factorial(int n, int acc) {
if (n == 0) {
return acc;
}
else {
return tr_factorial(n-1, acc*n);
}
} // tr_factorial
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:13:14 1997.
This page generated on Wed Nov 5 12:38:37 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu