import java.math.BigInteger;
import java.util.Vector;
public class FactorialBigIntegerVector
{
protected static Vector<BigInteger> resultstable = new Vector<BigInteger>();
//guarantee that the value of the first element is always 1
static
{ resultstable.addElement( BigInteger.valueOf( 1 ) );
}
//multi thread safe
public static synchronized BigInteger factorial( int x )
{
if( x < 0 ) throw new IllegalArgumentException( "x must be non-negative" );
for( int size = resultstable.size(); size <= x; size++ )
{
BigInteger previousfactorial = (BigInteger) resultstable.elementAt( size - 1 );
BigInteger nextfactorial = previousfactorial.multiply( BigInteger.valueOf(size) );
resultstable.addElement( nextfactorial );
}
return (BigInteger) resultstable.elementAt( x );
}
public static void main( String[] args )
{
for( int i = 1; i < 50; i++ )
{
System.out.println( i + "! = " + factorial( i ) );
}
}
}