Compute the factorial of a value Use this method for large values. - Android java.lang

Android examples for java.lang:Math

Description

Compute the factorial of a value Use this method for large values.

Demo Code


//package com.java2s;

import java.util.ArrayList;

public class Main {
    private static ArrayList<Long> factorialCache = new ArrayList<Long>();

    /**// w ww  . java 2  s.com
     * Compute the factorial of a value
     * Use this method for large values. For small values, you can use <code>factorial</code>
     * 
     * @param n must be >= 0
     * @return the factorial value
     * @see factorial
     */
    public static long factorial2(int n) {
        if (n >= factorialCache.size()) {
            factorialCache.add(n, n * factorial(n - 1));
        }

        return factorialCache.get(n);
    }

    /**
     * Compute the factorial of a value
     * Use this method for small values. For larger values, use <code>factorial2</code>
     * 
     * @param n must be >= 0
     * @return the factorial value
     * @see factorial2
     */
    public static long factorial(int n) {
        if (n <= 1)
            return 1;
        else
            return n * factorial(n - 1);
    }
}

Related Tutorials