Friday, September 14, 2007

Computing Factorial using BigDecimal

This demonstration program computes the factorial using BigDecimal. However, there exists more efficient algorithms, see http://www.luschny.de/math/factorial/FastFactorialFunctions.htm

import java.math.BigInteger;

public class FactorialTest {    
    public static void main(String[] args) {
        long l = 10000;
        BigInteger bi = factorial(l);
        System.out.println(bi);
        System.out.println(bi.toString().length());
    }
    
    /* ordinary factorial code */
    public static long factorial(int n) {
        long f = 1;
        
        while (n > 1) {
            f *= n--;
        }
        
        return f;
    }
    
    /* BigInteger factorial code */
    public static BigInteger factorial(long n) {
        BigInteger f = BigInteger.ONE;              // long f = 1;
        BigInteger g = BigInteger.valueOf(n);       // int n
        
        while (g.compareTo(BigInteger.ONE) == 1) {  // while (n > 1) {
            f = f.multiply(g);                      // f *= n;
            g = g.subtract(BigInteger.ONE);         // n--;
        }
        
        return f;
    }
}

No comments: