FileDocCategorySizeDatePackage
Factorial4.javaAPI DocExample2018Mon Sep 22 13:30:30 BST 1997None

Factorial4

public class Factorial4 extends Object
This version of the program uses arbitrary precision integers, so it does not have an upper-bound on the values it can compute. It uses a Vector object to cache computed values instead of a fixed-size array. A Vector is like an array, but can grow to any size. The factorial() method is declared "synchronized" so that it can be safely used in multi-threaded programs. Look up java.math.BigInteger and java.util.Vector while studying this class.

Fields Summary
protected static Vector
table
Constructors Summary
Methods Summary
public static synchronized java.math.BigIntegerfactorial(int x)
The factorial() method, using BigIntegers cached in a Vector

       // create cache
    table.addElement(BigInteger.valueOf(1)); 
    if (x < 0) throw new IllegalArgumentException("x must be non-negative.");
    for(int size = table.size(); size <= x; size++) {
      BigInteger lastfact = (BigInteger)table.elementAt(size-1);
      BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
      table.addElement(nextfact);
    }
    return (BigInteger) table.elementAt(x);
  
public static voidmain(java.lang.String[] args)
A simple main() method that we can use as a standalone test program for our factorial() method.

    for(int i = 1; i <= 50; i++) System.out.println(i + "! = " + factorial(i));