fibonacci tail recursive - java

jino630·2021년 6월 16일
0

recursive

목록 보기
4/4
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        }

        int total = 0;
        int n1 = 0;
        int n2 = 1;

        for (int i = 0; i < (n - 1); ++i) {
            total = n1 + n2;
            n1 = n2;
            n2 = total;
        }

        return total;
    }

    public static int fibonacciRecursive(int n) {
        if (n <= 1) {
            return n;
        }

        return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
    }

    public static int fibonacciTailRecursive(int n, int n1, int n2) {
        if (n < 1) {
            return n1;
        }

        return fibonacciTailRecursive(n - 1, n2, n1 + n2);
    }

0개의 댓글