- 1.
- You are probably getting sick of the factorial
method by now, but just for practice, write an iterative
version of factorial. Put it in a new project named
Big.prj.
- 2.
- Print a table of the integers from 0 to 30 along with their
factorials. At some point around 15, you will probably see
that the answers are not right any more. Why not?
- 3.
- Go to the Sun web page that contains all the Java
documentation; there is a link to it from the class web
page. Click on the java.math package and then click
on the BigInteger class. Print the documentation of the
BigInteger class. Read it.
BigIntegers are built-in objects that can represent
arbitrarily-big integers. There is no upper bound except
the limitations of memory size and processing speed.
- 4.
- There are several ways to create a new
BigInteger, but the one I recommend uses valueOf.
The following code converts an integer to a BigInteger:
int x = 17;
BigInteger big = BigInteger.valueOf (x);
Type in this code and try out a few simple cases like creating a
BigInteger and printing it. Notice that println knows how to
print BigIntegers! Don't forget to add import
java.math.BigInteger to the beginning of your program.
- 5.
- Unfortunately, because BigIntegers are not primitive types,
we cannot use the usual math operators on them. Instead we
have to use object methods like add. In order to
add two BigIntegers, you have to invoke add on one
of the objects and pass the other as an argument. For example:
BigInteger small = BigInteger.valueOf (17);
BigInteger big = BigInteger.valueOf (1700000000);
BigInteger total = small.add (big);
Try out some of the other methods, like multiply and
pow.
- 6.
- Convert factorial so that it performs its calculation
using BigIntegers, and then returns the BigInteger as a result.
You can leave the parameter alone--it will still be an integer.
- 7.
- Try printing the table again with your modified factorial
function. Is it correct up to 30? How high can you make it go? On
my machine, I calculated the factorial of all the numbers from 0 to
999, but it took over 2 minutes. The last number, 999!, has 2565
digits.