// MyMath.java // static methods demonstrating recursion // To run: MyMath.fib(4) in the Interactions pane public class MyMath { // Returns n! // Assumes that n is non-negative public static int factorial(int n) { if (n == 0) { // base case return 1; } else { // recursive case return n * factorial(n-1); } } // Returns the n-th Fibonacci number // Assumes that n is non-negative public static int fib(int n) { if (n == 0) { // base case 1 return 0; } else if (n == 1) { // base case 2 return 1; } else { // recursive case return fib(n-1) + fib(n-2); } } // Returns the n-th Fibonacci number // Much more efficient version that keeps // track of the previous two numbers public static int fib2(int n) { if (n == 0) return 0; int prevfib = 0; int fib = 1; for (int i = 2; i <= n; i++) { int newfib = fib + prevfib; prevfib = fib; fib = newfib; } return fib; } // Challenge: implement a recursive version // of the efficient algorithm! }