factorial tail recursive - java

jino630·2021년 6월 16일
0

recursive

목록 보기
3/4
    // for
    public static int factorial(int n) {
        int total = 1;

        for (int i = 1; i <= n; ++i) {
            total *= i;
        }

        return total;
    }

    // recursive
    public static int factorialRecursive(int n) {
        if (n <= 1) {
            return n;
        }

        return n * factorialRecursive(n - 1);
    }

    // tail recursive
    public static int factorialTailRecursive(int n, int total) {
        if (n <= 1) {
            return total;
        }

        return factorialTailRecursive(n - 1, n * total);
    }

0개의 댓글