First of all, you need to introduce a variable int sum = 0;
to store the value of the alternate series.
To only sum every second value, you should skip every second value. You can check that using the modulo operation, e.g. if( counter % 2 == 1 )
.
If that is true, you can add/subtract the current value of prod to the sum.
To get the alternating part, you can use a boolean positive = true;
like this:
if( positive ) {
sum += prod;
} else {
sum -= prod;
}
positive = !positive;
Based on the boolean
, the prod is either added or subtracted. The value is altered afterwards.
Because factorials become very large very fast, it would be better to use variables of type long
.