Java Reference

In-Depth Information

}

static BigInteger factorial(BigInteger n)

{

if (n.equals(BigInteger.ZERO))

return BigInteger.ONE;

else

return

n.multiply(factorial(n.subtract(BigInteger.ONE)));

}

}

comparison reveals the largest argument that can be passed to each of the first three

methodsbeforethereturnedfactorialvaluebecomesmeaningless,becauseoflimitson

the range of values that can be accurately represented by the numeric type.

The first version is based on
int
and has a useful argument range of0through 12.

Passing any argument greater than 12 results in a factorial that cannot be represented

accurately as an
int
.

Youcanincreasetheusefulrangeof
factorial()
,butnotbymuch,bychanging

theparameterandreturntypesto
long
.Aftermakingthesechanges,youwilldiscover

that the upper limit of the useful range is 20.

To further increase the useful range, you might create a version of
factorial()

whoseparameterandreturntypesare
double
.Thisispossiblebecausewholenumbers

canberepresentedexactlyas
double
s.However,thelargestusefulargumentthatcan

bepassedis170.0.Anythinghigherthanthisvalueresultsin
factorial()
returning

+infinity.

Itispossiblethatyoumightneedtocalculateahigherfactorialvalue,perhapsinthe

contextofcalculatingastatisticsprobleminvolvingcombinationsorpermutations.The

onlywaytoaccuratelycalculatethisvalueistouseaversionof
factorial()
based

on
BigInteger
.

When you run this application, as in
java FactComp
, it generates the following

output:

479001600

2432902008176640000