Recursive factorial method - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Recursive factorial method

Demo Code


//package com.java2s;

public class Main {
    /**//from  w w w  .  j a va2 s.  c  om
     * Recursive factorial method
     * @pre n >= 0
     * @param n The integer whose factorial is being computed
     * @return n!
     */
    public static int factorialRecursive(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    /**
     * Calculate the factorial of n
     * Pre: 0 <= n <= 12
     * @param n The integer whose factorial is being computed
     * @return n!
     */
    public static int factorial(int n) {
        int result = 1;
        while (n > 0) {
            result *= n--;
        }
        return result;
    }
}

Related Tutorials