How do I implement Tail recursion with my Fibonacci method?

爷,独闯天下 提交于 2019-12-02 06:23:27

A simple recursion to achieve the series you want could be :

public class FibRecursion{

    private static BigInteger[] fval;

    public static void main(String[] args) {

        int index = 10;
        fval = new BigInteger[index];
        fib(0,1,0,index);
        System.out.println(Arrays.toString(fval));
    }

    public static void fib(long a, long b, int index, int endIndex ) {

        if (index >= endIndex) {

            return ;
        }

        fval[index] = BigInteger.valueOf(a).add(BigInteger.valueOf(b));
        index++;
        fib(b, a+b, index , endIndex);
    }
}

To avoid stack limitations, you can limit the recursion depth and do the resurrection in a few "pieces". Here is an example of a series of 50 elements, calculated with depth limited to 10 (RECURRSION_DEPTH = 10):

public class FibRecursion{

    private static BigInteger[] fval;
    //limit of the recursion depth. valid values are >=2
    private final static int RECURRSION_DEPTH = 10;

    public static void main(String[] args) {

        int index = 50;
        fval = new BigInteger[index];

        BigInteger aValue = BigInteger.valueOf(0);
        BigInteger bValue = BigInteger.valueOf(1);
        int startIndex = 0;
        int endIndex = RECURRSION_DEPTH;

        while (endIndex > startIndex) {

            fib(aValue,bValue,startIndex,endIndex);

            aValue = fval[endIndex-2];
            bValue = fval[endIndex-1];
            startIndex = endIndex;
            endIndex = Math.min(endIndex + RECURRSION_DEPTH, index);
        }

        System.out.println(Arrays.toString(fval));
    }

    //use BigInteger to avoid integer max value limitation 
    public static void fib(BigInteger a, BigInteger b, int index, int endIndex ) {

        if (index >= endIndex) {

            return ;
        }

        fval[index] = a.add(b);
        index++;
        fib(b, a.add(b), index , endIndex);
    }
}

This of course has other limitations, not related to stack size.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!