Java Reference
In-Depth Information
Example 1−9: Factorial3.java (continued)
static { table[0] = 1; } // factorial of 0 is 1.
// Remember the highest initialized value in the array
static int last = 0;
public static long factorial(int x) throws IllegalArgumentException {
// Check if x is too big or too small. Throw an exception if so.
if (x >= table.length) // ".length" returns length of any array
throw new IllegalArgumentException("Overflow; x is too large.");
if (x<0) throw new IllegalArgumentException("x must be non-negative.");
// Compute and cache any values that are not yet cached.
while(last < x) {
table[last + 1] = table[last] * (last + 1);
last++;
}
// Now return the cached factorial of x.
return table[x];
}
}
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! or 100! ? The java.math.Big-
Integer 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:
30414093201713378043612608166064768844377641568960512000000000000
Example 1-10 introduces the import statement. This statement must appear at the
top of a Java file, before any class is defined (but after the package declaration). It
provides a way to tell the compiler what classes you are using in a program. Once
a class like java.math.BigInteger has 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, is com.davidflana-
gan.examples.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 com-
puted 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
Search WWH ::




Custom Search