factorial tail recursive - java


    // 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);
    }