java.math.BigIntegerjava.Math.BigInteger.
Here is a program with int and BigInteger solutions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// numbers/Factorial.java - Computes factorial
// Fred Swartz - 2003-11-02
import java.math.BigInteger;
public class Factorial {
public static void main(String[] args) {
//-- BigInteger solution.
BigInteger n = BigInteger.ONE;
for (int i=1; i<=20; i++) {
n = n.multiply(BigInteger.valueOf(i));
System.out.println(i + "! = " + n);
}
//-- int solution (BAD IDEA BECAUSE ONLY WORKS TO 12).
int fact = 1;
for (int i=1; i<=20; i++) {
fact = fact * i;
System.out.println(i + "! = " + fact);
}
}
}
|
An int produces pure garbage after 12, and long
only makes it to 20. The shame of integer arithmetic is that it
doesn't stop when the values are bad -- it just produces garbage by
throwing away bits in the result that don't fit in an int (32 bits)
or long (64-bits).
BigInteger values are limited only
by the amount of memory.
|
|