Computing Big Factorials
In the previous section, we learned that 20! is the largest factorial that can fit in a 64-bit integer. But what if you want to compute 50! or100!? The java.math.BigInteger class represents arbitrarily large integer values and provides methods to perform arithmetic operations on these very large numbers. Example 1-10 uses the BigInteger class to compute factorials of any size. It also includes a simple main( )method that defines a standalone test program for our factorial( ) method. This test program says, for example, that 50! is the following 65-digit number:
30414093201713378043612608166064768844377641568960512000000000000Example 1-10 introduces the import statement. This statement must appear at the top of a Java file, before any class is defined (but after thepackage declaration). It provides a way to tell the compiler what classes you are using in a program. Once a class like java.math.BigIntegerhas been imported, you no longer have to type its full name; instead you can refer to it simply as BigInteger. You can also import an entire package of classes, as with the line:
import java.util.*Note that the classes in the java.lang package are automatically imported, as are the classes of the current package, which, in this case, isje3.basics.
Example 1-10 uses the same caching technique Example 1-9 did. However, because there is no upper bound on the number of factorials that can be computed with this class, you can’t use a fixed-sized array for the cache. Instead, use the java.util.ArrayList class, which is a utility class that implements an array-like data structure that can grow to be as large as you need it to be. Because an ArrayList is an object rather than an array, you use such methods as size( ), add( ), and get( ) to work with it. By the same token, a BigInteger is an object rather than a primitive value, so you can’t simply use the * operator to multiply BigInteger objects. Use the multiply( ) method instead.