那
public static void printFactorials (int max) {
long fac = 1;
long sum = 0;
for (int i = 1; i <= max; fac *= ++i) {
System.out.println(String.format("Factorial(%2d)=%d", i, fac));
sum += fac;
}
System.out.println(String.format("Sum of Factorials(1 to %2d)=%d", max, sum));
}
给你
Factorial( 1)=1
Factorial( 2)=2
Factorial( 3)=6
Factorial( 4)=24
Factorial( 5)=120
Factorial( 6)=720
Factorial( 7)=5040
Factorial( 8)=40320
Factorial( 9)=362880
Factorial(10)=3628800
Factorial(11)=39916800
Factorial(12)=479001600
Factorial(13)=6227020800
Factorial(14)=87178291200
Factorial(15)=1307674368000
Sum of Factorials(1 to 15)=1401602636313
long
21 开始失败,下一步是BigInteger
public static void printRlyBigFactorials (int max) {
BigInteger fac = BigInteger.ONE;
BigInteger sum = BigInteger.ZERO;
for (int i = 1; i <= max; ++i) {
fac = fac.multiply(BigInteger.valueOf(i));
sum = sum.add(fac);
System.out.println(String.format("Factorial(%2d)=%d", i, fac));
}
System.out.println(String.format("Sum of Factorials(1 to %2d)=%d", max, sum));
}
这几乎可以无限期地工作,并且可以为您提供精美的结果,例如:
Sum of Factorials(1 to 500)=
1222581999810786173488382263893486121736784649845260488587055662127413631697
9142090995417259894466676137016242713788312106218384177808117660024733369428
7060019503701220190523381023699528466605036804597249531428694859689049295904
5138704466475196055082304091214424335155644013903958356823605973150159110295
5787828433482529258832635575855564789877227459384652114477297831606218655683
9245588828671235437927278554210732477499719243692398907465554636521289870187
5799458234466791378320221140358905721655475503366304295011345436395868843079
5463780536087239619245051615759218253091986494512882003123090598805090122753
7135918455294416676103707115038417384516670399033063650562275830354903359872
0775172343137459008549361297203752431405977559950082400276439557196120290170
5516606073135650288107937474531851451830365876392678959480905477335825506233
3795849463603798966643420966668878072957663827751761832039623225350606860709
6479320263132522604054741925038640750661849690108363701190203548476572823422
7743271977187818002695582046473911765828511673121820261887951566200568565033
40092247479478684738621107994804323593105039052556442336528920420940313