As others have mentioned, you're overflowing the size of int
. Changing to long
can handle up to 20, but it will overflow too at any higher value, at which point you'd need BigInteger
.
However, you have much bigger problems than that.
Your main problem is that your algorithm is bad.
You're supposed to be calculating this:
1 + 2 ! + 3 ! + 4 ! + 5 ! + ...
1 + 1*2 + 1*2*3 + 1*2*3*4 + 1*2*3*4*5 + ...
1 + 2 + 6 + 24 + 120 + ...
So let's add some print statements to see what you're really doing. See updated code and output below.
1 + 1+2 + 2+4+12 + 12+24+72+288 + 288+576+1728+6912+34560 + ...
WOW! That's not even close to the same thing.
I'll leave it to you to figure out where you went wrong.1
Those print statements will help with that.
1) Hint: Remove i
loop.
Code
int sum = 0;
int a = 1;
System.out.printf(" a=%-11d sum=%d%n", a, sum);
for (int j = 1; j < 21; j++) {
for(int i=1;i<j+1;i++) {
a = a * i;
sum += a;
System.out.printf("j=%-2d i=%-2d a=%-11d sum=%d%n", j, i, a, sum);
}
}
System.out.println("sum=" + sum);
Output
a=1 sum=0
j=1 i=1 a=1 sum=1
j=2 i=1 a=1 sum=2
j=2 i=2 a=2 sum=4
j=3 i=1 a=2 sum=6
j=3 i=2 a=4 sum=10
j=3 i=3 a=12 sum=22
j=4 i=1 a=12 sum=34
j=4 i=2 a=24 sum=58
j=4 i=3 a=72 sum=130
j=4 i=4 a=288 sum=418
j=5 i=1 a=288 sum=706
j=5 i=2 a=576 sum=1282
j=5 i=3 a=1728 sum=3010
j=5 i=4 a=6912 sum=9922
j=5 i=5 a=34560 sum=44482
j=6 i=1 a=34560 sum=79042
j=6 i=2 a=69120 sum=148162
j=6 i=3 a=207360 sum=355522
j=6 i=4 a=829440 sum=1184962
j=6 i=5 a=4147200 sum=5332162
j=6 i=6 a=24883200 sum=30215362
j=7 i=1 a=24883200 sum=55098562
j=7 i=2 a=49766400 sum=104864962
j=7 i=3 a=149299200 sum=254164162
j=7 i=4 a=597196800 sum=851360962
j=7 i=5 a=-1308983296 sum=-457622334
j=7 i=6 a=736034816 sum=278412482
j=7 i=7 a=857276416 sum=1135688898
Here you can also see your overflow problem occurring (the first time) at j=7, i=5
.