/** * Computing fibonacci numbers recursively. * The core idea here is that there is a public method which allows the user * to say "I want the nth fibb number", and a private recursive function that * does the wark using some extra parameters that the public metod does not, and * should not, have * * @author gtowell * Created: Aug 11, 2021 */ import java.math.BigInteger; public class Fibb { /** * Private recursive function for doign fibonacci * @param fibNumA the smaller number * @param fibNumB the larger number * @param counter home much work is still to be done * @return the Nth fibb number */ private BigInteger fibonacciUtil(BigInteger fibNumA, BigInteger fibNumB, int counter) { //System.out.println(counter + " " + fibNumA + " " + fibNumB); if (counter==1) return fibNumA.add(fibNumB); return fibonacciUtil(fibNumB, fibNumA.add(fibNumB), counter-1); } /** * Return the Nth fibonacci number. * @param n the fibb number to calculate * @return the Nth fibb number */ public BigInteger fibonacci(int n) { // check that n is valid if (n<=0) return BigInteger.valueOf(0); if (n < 3) return BigInteger.valueOf(1); // call private func to do the calculation return fibonacciUtil(BigInteger.valueOf(1), BigInteger.valueOf(1), n-2); } public static void main(String[] args) { Fibb fib = new Fibb(); for (int i=0; i<16; i++) System.out.println("Fibb number " + i + " = " + fib.fibonacci(i)); } }