import java.math.BigInteger; import java.util.ArrayList; /** * Simple recursion functions * * @author gtowell * Created: Oct 2019 * Modified: Feb 2020 */ public class Recurser { /** * A bad recursive function. It lacks a base case so the recursion does not stop. * @param c the number to count down from */ public void badRecurse(int c) { System.out.println("A" + c); badRecurse(c-1); } /** * A good recursive function to count down from a number * @param c the number to count down from */ public void goodRecurse(int c) { System.out.println("B" + c); if (c<=0) return; goodRecurse(c-1); } /** * Recursively compute fibonacci numbers * The private version that actually does recursion * @param fibNumA a fib number * @param fibNumB the next fib number in the series for fibNumA * @param counter the number of additional steps to take in the series * @return the counterth fib number */ private BigInteger iFibonacci(BigInteger fibNumA, BigInteger fibNumB, int counter) { System.out.println(counter + " " + fibNumA + " " + fibNumB); if (counter==1) return fibNumA.add(fibNumB); return iFibonacci(fibNumB, fibNumA.add(fibNumB), counter-1); } /** * Compute the nth fibonacci number * @param n the index of the desired number * @return the nth fibonacci number */ public BigInteger fibonacci(int n) { if (n<=0) // make sure that the number being asked for is reasonable return BigInteger.valueOf(0); if (n<3) return BigInteger.valueOf(1); return iFibonacci(BigInteger.valueOf(1), BigInteger.valueOf(1), n-2); } /** * A recursive function to add two positive numbers * @param num1 one of the numbers * @param num2 another number * @return the sum of the two numbers */ public int rAdder(int num1, int num2) { if (num2<=0) return num1; return rAdder(num1+1, num2-1); } public ArrayList rAccmulate(int count) { if (count == 0) return new ArrayList(); ArrayList alAcc = rAccmulate(count-1); alAcc.add(count); return alAcc; } /** * Implement multiplication recursively using addition * For example, given the args 7 and 4 write a recusive function * that computes 7+7+7+7 * @param i1 a number * @param i2 another number * @return i1*i2 */ public int multiply(int i1, int i2) { return 0; } /** * Write a recusrsive function to add all the values in the array * Hint, this method should not be recursive. Rather make a * private recursive function and call that from here * @param array * @return the sum of the numbers in the array */ public int addArray(int[] array) { return 0; } public static void main(String[] args) { Recurser r = new Recurser(); //r.badRecurse(100); //r.goodRecurse(100); System.out.println("Result: " + r.fibonacci(472)); //System.out.println(r.rAdder(5, 6)); System.out.println(r.rAccmulate(10)); } }