Java BigInteger Factorial factorial(BigInteger n)

Here you can find the source of factorial(BigInteger n)

Description

Compute the Factorial of n, often written as c! in mathematics.

License

Open Source License

Parameter

Parameter Description
n Note: n &gt;= 0. This BigInteger <code>n</code> will be 0 after this method finishes.

Return

n * (n-1) * (n-2) * ... * 1

Declaration

public static BigInteger factorial(BigInteger n) 

Method Source Code


//package com.java2s;
/*//from ww  w  . ja  va  2s  .  co m
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures
    
 Copyright (C) 2015
 Ludwig-Maximilians-Universit?t M?nchen
 Lehr- und Forschungseinheit f?r Datenbanksysteme
 ELKI Development Team
    
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.
    
 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.math.BigInteger;

public class Main {
    /**
     * Compute the Factorial of n, often written as <code>c!</code> in
     * mathematics.
     * <p>
     * Use this method if for large values of <code>n</code>.
     * </p>
     *
     * @param n Note: n &gt;= 0. This {@link BigInteger} <code>n</code> will be 0
     *        after this method finishes.
     * @return n * (n-1) * (n-2) * ... * 1
     */
    public static BigInteger factorial(BigInteger n) {
        BigInteger nFac = BigInteger.ONE;
        while (n.compareTo(BigInteger.ONE) > 0) {
            nFac = nFac.multiply(n);
            n = n.subtract(BigInteger.ONE);
        }
        return nFac;
    }

    /**
     * Compute the Factorial of n, often written as <code>c!</code> in
     * mathematics.
     *
     * @param n Note: n &gt;= 0
     * @return n * (n-1) * (n-2) * ... * 1
     */
    public static long factorial(int n) {
        long nFac = 1;
        for (long i = n; i > 0; i--) {
            nFac *= i;
        }
        return nFac;
    }
}

Related

  1. factorial(BigInteger n)
  2. factorial(BigInteger number)
  3. factorial(BigInteger originValue)