Search code examples
javaloopsseriesfactorial

Alternating factorial terms using Java


I'm trying to write a loop in Java that can output the sum of a series which has this form... 1! -3! + 5! – 7! + ... up to n (user gives n as a positive odd number). For example, if the user inputs 5 for n, then the series should calculate the sum of 1! -3! + 5! (hard part) & display it to the user with a basic print statement (easy part). If the user gives 9, then the sum calculated would come from 1! -3! + 5! - 7! + 9!.

For ease, just assume the user always puts in a positive odd number at any time. I'm just concerned about trying to make a sum using a loop for now.

The closest code I've come up with to do this...

int counter = 1;
int prod = 1;   
n = console.nextInt(); 
while (counter <= n) 
{                  
    prod = prod * counter;
    counter++; 
}   
System.out.println(prod);

This does n!, but I'm finding it hard to get it do as specified. Any pointers would be great.


Solution

  • 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.